package View;

import Module.ResourceProject;
import Module.addUserRoles;
import Client.Client;
import Module.ActionList;
import Module.Session;
import Module.Team;
import Module.User;
import Module.Activity;
import Module.DecisionList;
import Module.Resource;
import Module.ResourceType;
import Shared.Server;
import com.itextpdf.text.DocumentException;
import java.awt.AWTException;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.*;
import java.awt.Robot;


/**
 *
 * @author CCD gruppe 2
 */
public class GUI {

    ActivityInfoPanel activityInfoPanel;
    AddUsersToProjectFrame addUsersToProjectFrame;
    CalendarFrame calendarFrame;
    ChatPanel chatPanel;
    ActivityListPanel activityListPanel;
    LoginFrame loginFrame;
    MainFrame mainFrame;
    MainSessionPanel mainSessionPanel;
    SessionPlan sessionPlan;
    ActivityTabPanel activityTabPanel;
    NewProjectFrame newProjectFrame;
    ProjectInfoPanel projectInfoPanel;
    SessionPanelForTabbedPane sessionPanel = new SessionPanelForTabbedPane();
    Client client;
    AddUserFrame addUserFrame;
    EditUserFrame editUserFrame;
    ResourceFrame resourceFrame;
    ResourceToProjectFrame resourceToProjectFrame;
    RemoveTeamButtonListener rtbl = new RemoveTeamButtonListener();
    ArrayList<Team> teams = new ArrayList<Team>();
    ArrayList<Activity> activities = new ArrayList<Activity>();
    WelcomeTabPanel welcomeTabPanel;
    IpFrame ipFrame;
    public TextFieldClickListener tfcl;
    public SessionTeamMemberListSelectionListener stmlsl = new SessionTeamMemberListSelectionListener();
    String userName = "";
    DecisionListFrame decisionListFrame;
    AddDecisionListItemFrame addDecisionListItemFrame;
    ArrayList<DecisionList> decisionlist = new ArrayList<DecisionList>();
    ArrayList<ActionList> actionlist = new ArrayList<ActionList>();
    ActionListFrame actionListFrame;
    UserlistFrame userlistFrame;
    ArrayList<User> allUsers;

    public GUI(final Client client) {
        this.client = client;
        loginFrame = new LoginFrame();
        loginFrame.setVisible(true);
        mainFrame = new MainFrame();
        addUsersToProjectFrame = new AddUsersToProjectFrame();
        calendarFrame = new CalendarFrame();
        userlistFrame = new UserlistFrame();
        chatPanel = mainFrame.getChatPanel();
        mainSessionPanel = mainFrame.getMainSessionPanel();
        resourceFrame = new ResourceFrame();
        resourceToProjectFrame = new ResourceToProjectFrame();
        activityTabPanel = mainFrame.getActivityTabPanel();
        activityListPanel = activityTabPanel.getActivityListPanel();
        activityInfoPanel = activityTabPanel.getActivityInfoPanel();
        welcomeTabPanel = mainFrame.getWelcomeTabPanel();
        addUserFrame = new AddUserFrame();
        editUserFrame = new EditUserFrame();
        decisionListFrame = new DecisionListFrame();
        addDecisionListItemFrame = new AddDecisionListItemFrame();
        actionListFrame = new ActionListFrame();
        actionListFrame.setVisible(false);
        newProjectFrame = new NewProjectFrame();
        projectInfoPanel = newProjectFrame.getProjectInfoPanel();
        tfcl = new TextFieldClickListener();
        ipFrame = new IpFrame();
        ipFrame.setVisible(false);

        mainSessionPanel.getCreateSessionPlanButton().setVisible(false);
        resourceToProjectFrame.setVisible(false);
        resourceFrame.getNewTypeButton().addActionListener(new resourceButtonListener());
        resourceFrame.getSaveButton().addActionListener(new resourceButtonListener());
        resourceFrame.getCloseButton().addActionListener(new resourceButtonListener());
        resourceFrame.setVisible(false);
        resourceFrame.getjLabel4().setVisible(false);
        resourceFrame.getResourceTypeTextField().setVisible(false);
        activityListPanel.setVisible(false);
        activityInfoPanel.setVisible(false);
        mainSessionPanel.getAddNewSessionButton().setVisible(false);
        mainSessionPanel.getRemoveSessionButton().setVisible(false);
        mainSessionPanel.getEditSessionButton().setVisible(false);
        decisionListFrame.setVisible(false);
        addDecisionListItemFrame.setVisible(false);
        decisionListFrame.getCloseDecisionListButton().addActionListener(new DecisionListButtonListener());
        decisionListFrame.getNewDecisionButton().addActionListener(new DecisionListButtonListener());
        decisionListFrame.getEditDecisionButton().addActionListener(new DecisionListButtonListener());
        decisionListFrame.getSaveDecisionListButton().addActionListener(new DecisionListButtonListener());
        addDecisionListItemFrame.getCloseDecisionListItemButton().addActionListener(new NewDecisionListItemButtonListener());
        addDecisionListItemFrame.getSaveDecisionListItemButton().addActionListener(new NewDecisionListItemButtonListener());        

        JMenuItem newResource = new JMenuItem("Ny ressurs");
        JMenuItem decisionList = new JMenuItem("Beslutningsliste");

        newResource.addActionListener(new resourceMenuActionListener());
        decisionList.addActionListener(new resourceMenuActionListener());

  
        JMenuItem actionList = new JMenuItem("Aksjonsliste");
        JMenuItem projectResources = new JMenuItem("Prosjektressurser");
        projectResources.addActionListener(new resourceMenuActionListener());
        actionList.addActionListener(new resourceMenuActionListener());
        mainFrame.getResourceMenu().add(newResource);
        mainFrame.getResourceMenu().addSeparator();
        mainFrame.getResourceMenu().add(projectResources);

        actionListFrame.getStartDateTextField().addMouseListener(tfcl);
        actionListFrame.getEndDateTextField().addMouseListener(tfcl);

        WindowListener wl = new WindowListener();
        chatPanel.getInputText().addKeyListener(new ChatTextListener());
        mainFrame.addWindowListener(wl);

        ActivityListSelectionListener alml = new ActivityListSelectionListener();
        activityListPanel.getActivityJList().addMouseListener(alml);

        BoundToSessionActivityListener btsal = new BoundToSessionActivityListener();
        activityInfoPanel.getBoundToSessionDropDown().addActionListener(btsal);

        CreateProjectButtonListener cpbj = new CreateProjectButtonListener();
        projectInfoPanel.getCreateProjectButton().addActionListener(cpbj);

        AddSessionButtonListener asbl = new AddSessionButtonListener();
        RemoveSessionButtonListener rsbl = new RemoveSessionButtonListener();
        CreateSessionPlanListener cspl = new CreateSessionPlanListener();
        SaveSessionButtonListener ssbl = new SaveSessionButtonListener();
        mainSessionPanel.getAddNewSessionButton().addActionListener(asbl);
        mainSessionPanel.getRemoveSessionButton().addActionListener(rsbl);
        mainSessionPanel.getCreateSessionPlanButton().addActionListener(cspl);
        mainSessionPanel.getEditSessionButton().addActionListener(ssbl);
        mainSessionPanel.getAddMeButton().addActionListener(new VoiceListButtonListener());
        mainSessionPanel.getRemoveMeButton().addActionListener(new VoiceListButtonListener());
        mainSessionPanel.getNewCountdownButton().addActionListener(new CountDownButtonListener());
        mainSessionPanel.getStopCountdownButton().addActionListener(new CountDownButtonListener());

        TeamTabListener ttl = new TeamTabListener();
        addUsersToProjectFrame.getTeamsTabbedPane().addChangeListener(ttl);

        ExpertiseListSelectionListener elsl = new ExpertiseListSelectionListener();
        addUsersToProjectFrame.getUsersList().addListSelectionListener(elsl);

        SaveActivityButtonListener sabl = new SaveActivityButtonListener();
        activityInfoPanel.getSaveActivityButton().addActionListener(sabl);

        DeleteActivityButtonListener dabl = new DeleteActivityButtonListener();
        activityListPanel.getDeleteActivityButton().addActionListener(dabl);

        resourceToProjectFrame.getFromeDateTextField().addMouseListener(tfcl);
        resourceToProjectFrame.getToDateTextField().addMouseListener(tfcl);

        ipFrame.getSaveButton().addActionListener(new IPFramButtonListener());
        loginFrame.getIPMenu().addMouseListener(new IPMenuActionListener());


        userlistFrame.getUserlistJList().addMouseListener(new UserlistFrameListSelectionListener());
        userlistFrame.getCloseButton().addActionListener(new CloseUserListFrameListener());

        userlistFrame.getEditUserButton().addActionListener(new EditUserInfoListener());

        actionListFrame.getCloseActivityListFrameButton().addActionListener(new ActionListButtonListener());
        actionListFrame.getRegretButton().addActionListener(new ActionListButtonListener());
        actionListFrame.getSaveActionListButton().addActionListener(new ActionListButtonListener());

        AvailableResourcesListSelectionListenener availablerlsl = new AvailableResourcesListSelectionListenener();
        resourceToProjectFrame.getAvailableResouceList().addMouseListener(availablerlsl);
        AddedResourcesListSelectionListener addedrlsl = new AddedResourcesListSelectionListener();
        resourceToProjectFrame.getSelectedResourcesList().addMouseListener(addedrlsl);

        projectInfoPanel.getAddProjectUsersButton().addActionListener(new AddUsersToProjectActionListener());

        resourceToProjectFrame.getAddResourceButton().addActionListener(new AddResourceActionListener());
        resourceToProjectFrame.getNewResourceButton().addActionListener(new NewResourceActionListener());

        resourceToProjectFrame.getRemoveResourceButton().addActionListener(new RemoteResourceActionListener());
        resourceToProjectFrame.getSaveButton().addActionListener(new SaveResourceActionListener());

        addUsersToProjectFrame.getAddUserButton().addActionListener(new AddUserToProjectButton());

        addUsersToProjectFrame.getNewTeamButton().addActionListener(new NewTeamButtonListener());

        addUsersToProjectFrame.getCloseButton().addActionListener(new CloseAddUsersToProjectFrameListener());

        addUsersToProjectFrame.getNewUserButton().addActionListener(new AddNewUserListener());
        CreateUserActionListener cua = new CreateUserActionListener();

        addUserFrame.getCreateUserButton().addActionListener(cua);

        editUserFrame.getCloseButton().addActionListener(new CloseEditUserFrameListener());

        addUsersToProjectFrame.getRemoveUserButton().addActionListener(new RemoteUserFromProjectListener());

        editUserFrame.getUpdateButton().addActionListener(new UpdateUserActionListener());

        activityListPanel.getNewActivityButton().addActionListener(new NewActivityButtonClickedListener());

        chatPanel.getSendButton().addActionListener(new ChatSendButtonListener());

    }

    /**
     * A method that updates the voice list.
     */
    public void updateVoiceList() {
        mainFrame.getMainSessionPanel().getVoiceListModel().clear();
        for (int i = 0; i < client.getUsersAddedToVoiceList().size(); i++) {
            mainFrame.getMainSessionPanel().getVoiceListModel().addElement(client.getUsersAddedToVoiceList().get(i).getFullname());
        }
    }

    /**
     * A method that updates the decision list.
     */
    public void updateDecisionList() {
        decisionListFrame.getIntroTextArea().setText(client.getDecisionListIntro(client.getSelectedProject().getId()));
        decisionlist = client.getDecisionListToProject(client.getSelectedProject().getId());
        decisionListFrame.setTabel(decisionlist, client.getSessions(), client.getSelectedProject().getName());
    }
    /**
     * A method that updates the action list.
     */
    public void updateActionList() {
        actionListFrame.getActionlistIntroTextArea().setText(client.getActionListIntro(client.getSelectedProject().getId()));
        ArrayList<ActionList> actionList = client.getActionListToProject(client.getSelectedProject().getId());
        actionListFrame.setTable(actionList, client.getProjectUsers());
    }
    /**
     * A method that updates the activity list.
     */
    public void updateActivityList() {
        if (client.getSelectedProject().getId() > 0) {
            activities = client.getActivitiesForSelectedProject();
            activityListPanel.getActivityListModel().clear();
            for (int i = 0; i < client.getNumberOfActivities(); i++) {
                activityListPanel.getActivityListModel().addElement(client.getActivitiesForSelectedProject().get(i).getActivityName());
            }

        }

    }
    /**
     * A method that updates the resources list.
     */
    public void updateResources() {
        ArrayList<Resource> resources = new ArrayList<Resource>();
        ArrayList<ResourceProject> resourceProject = client.getAllResourceToProject(client.getSelectedProject().getId());
        resourceToProjectFrame.clear();
        try {
            resources = client.getAllResource();
        } catch (RemoteException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int i = 0; i < resourceProject.size(); i++) {
            for (int j = 0; j < resources.size(); j++) {
                if (resourceProject.get(i).getResource().getId() == resources.get(j).getId()) {
                    resources.remove(j);
                }
            }

            resourceToProjectFrame.getSelectedResourceListModel().addElement(resourceProject.get(i).getResource().getName());
            resourceToProjectFrame.getSelectedResources().add(resourceProject.get(i).getResource());
            resourceToProjectFrame.getResourceProject().add(resourceProject.get(i));
        }
        for (int i = 0; i < resources.size(); i++) {
            resourceToProjectFrame.getAvailableResourceListModel().addElement(resources.get(i).getName());
            resourceToProjectFrame.getAvailableResources().add(resources.get(i));
        }
    }
    /**
     * A method that starts the countdown timer.
     * @param minutes
     */
    public void startCountDown(int minutes) {
        mainSessionPanel.countdown(minutes);
    }

    /**
     * A method that stops the countdown timer.
     */
    public void stopCountDown() {
        mainSessionPanel.stopCountdown();
    }
    /**
     * A method that resumes the countdown timer.
     */
    public void resumeCountDown() {
        mainSessionPanel.resumeCountdown();
    }
    /**
     * A method that shows the frame for adding users to a project.
     * @param text
     */
    public void showAddedUsersFrame(String text) {
        if (text.equals("Legg til brukere")) {
            if (addUsersToProjectFrame.getUsersListModel().isEmpty()) {
                ArrayList<User> users = client.getAllUsers();
                for (int i = 0; i < users.size(); i++) {
                    addUsersToProjectFrame.getUsersListModel().addElement(users.get(i).getFullname());
                    addUsersToProjectFrame.getUsers().add(users.get(i));
                }
            }
        } else {
            if (addUsersToProjectFrame.getUsersListModel().isEmpty()) {
                ArrayList<User> users = addUsersToProjectFrame.getUsers();
                for (int i = 0; i < users.size(); i++) {
                    addUsersToProjectFrame.getUsersListModel().addElement(users.get(i).getFullname());
                }
            }
        }
        addUsersToProjectFrame.setVisible(true);

    }

    /**
     * A method that shows the NewProjectFrame-window with cleared input.
     */
    public void newProjectClicked() {
        projectInfoPanel.clearInput();
        newProjectFrame.setVisible(true);
        addUsersToProjectFrame.clearInput();
        if(addUsersToProjectFrame.getTeamInfoPanels().size() == 0){
        newProjectFrame.getProjectInfoPanel().getAddProjectUsersButton().setText("Legg til brukere");
        newProjectFrame.getProjectInfoPanel().getCreateProjectButton().setText("Opprett");
        TeamInfoPanel infoPanel = new TeamInfoPanel();
        infoPanel.getTeamNameTextField().setText("Generell Session Support");
        infoPanel.getTeamNameTextField().setEditable(false);
        infoPanel.getFasilitatorCheckBox().setVisible(true);
        infoPanel.getSecretaryCheckBox().setVisible(true);
        infoPanel.getCustomerCheckBox().setVisible(true);
        infoPanel.getDeleteTeamButton().setVisible(false);
        infoPanel.getTeamMembersList().addListSelectionListener(new TeamMemberListSelectionListener());
        infoPanel.getFasilitatorCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        infoPanel.getSecretaryCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        infoPanel.getCustomerCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        addUsersToProjectFrame.addTeamTab(infoPanel, 0);
        }
    }

    /**
     * A method that adds a new teamtab.
     */
    public void newTeam() {
        TeamInfoPanel infoPanel = new TeamInfoPanel();
        infoPanel.getDeleteTeamButton().addActionListener(rtbl);
        infoPanel.getFasilitatorCheckBox().setVisible(false);
        infoPanel.getSecretaryCheckBox().setVisible(false);
        infoPanel.getCustomerCheckBox().setVisible(false);
        addUsersToProjectFrame.getTeamsTabbedPane().setVisible(true);
        infoPanel.getTeamMembersList().addListSelectionListener(new TeamMemberListSelectionListener());
        infoPanel.getFasilitatorCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        infoPanel.getSecretaryCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        infoPanel.getCustomerCheckBox().addActionListener(new TeamInfoPanelButtonListener());
        addUsersToProjectFrame.addTeamTab(infoPanel, 0);
    }

    /**
     * A method that shows objects that are bound to a project.
     */
    public void showProjectObjects() {
        mainSessionPanel.getAddNewSessionButton().setVisible(true);
        mainSessionPanel.getRemoveSessionButton().setVisible(true);
        mainSessionPanel.getCreateSessionPlanButton().setVisible(true);
        mainSessionPanel.getEditSessionButton().setVisible(true);
        mainSessionPanel.getVoiceListPanel().setVisible(true);
        mainSessionPanel.getTimerPanel().setVisible(true);
        activities.clear();
        activityListPanel.getActivityListModel().clear();
        activityListPanel.getActivityJList().clearSelection();
        activityListPanel.getActivityJList().setEnabled(true);
        activityListPanel.getDeleteActivityButton().setText("Slett");
        if (client.getNumberOfActivities() > 0) {
            activities = client.getActivitiesForSelectedProject();
            activityListPanel.getActivityListModel().clear();
            for (int i = 0; i < client.getNumberOfActivities(); i++) {
                activityListPanel.getActivityListModel().addElement(client.getActivitiesForSelectedProject().get(i).getActivityName());
            }
        }
        activityListPanel.setVisible(true);
        activityInfoPanel.setVisible(false);
        activityInfoPanel.getActivityNameTextField().setFocusable(false);
        mainSessionPanel.clearSessionPanels();
        ArrayList<Session> sessions = client.getSessions();
        teams = client.getTeamsToProject(client.getSelectedProject().getId());
        decisionlist = client.getDecisionListToProject(client.getSelectedProject().getId());
        actionlist = client.getActionListToProject(client.getSelectedProject().getId());
        mainFrame.setTitle(client.getSelectedProject().getName());
        chatPanel.getChatRoomForProjectLabel().setText("Chatterom for " + client.getSelectedProject().getName() + ":");
        chatPanel.getUserList().removeAll();
        chatPanel.activateChat();

        if (sessions.size() > 0) {
            updateSessionPanels();
        }
        updateVoiceList();
        setAdminToolsSessionPanel();
    }

    public void setAdminToolsSessionPanel() {
        if (!client.isAdmin()) {
            ArrayList<Team> t = client.getTeamsToProject(client.getSelectedProject().getId());
            int teamnumber = -1;
            for (int j = 0; j < t.size(); j++) {
                ArrayList<User> users = client.getUsersToTeam(t.get(j).getId());
                for (int k = 0; k < users.size(); k++) {
                    if (users.get(k).getId() == client.getUserToUsername(client.getLoginn().getUsername()).getId()) {
                        teamnumber = j;
                    }
                }
            }
            if(teamnumber!=0){
             mainSessionPanel.getRemoveSessionButton().setEnabled(false);
            mainSessionPanel.getAddNewSessionButton().setEnabled(false);
            mainSessionPanel.getCreateSessionPlanButton().setEnabled(false);
            
            }
           
        }
    }

    /**
     * A method that updates the sessionpanels.
     */
    public void updateSessionPanels() {
        mainFrame.getMainSessionPanel().clearSessionPanels();
        client.updateSessionList();
        ArrayList<Session> sessions = client.getSessions();
        mainSessionPanel.showSessionObjects();
        for (int i = 0; i < sessions.size(); i++) {
            mainFrame.getMainSessionPanel().addSessionPanel();
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).isInfoPanel();
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionName(sessions.get(i).getName());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionDate(sessions.get(i).getDate());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionPlace(sessions.get(i).getPlace());
            ArrayList<String> places = client.getAllPlaces();
            for (int j = 0; j < places.size(); j++) {
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getSessionPlaceModel().addElement(places.get(j));
            }
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionFromeTime(sessions.get(i).getStartTime());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionToTime(sessions.get(i).getEndTime());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getSessionPreparationTextArea().setText(sessions.get(i).getPreparation());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getSessionEvaluationTextArea().setText(sessions.get(i).getEvaluation());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).setSessionId(sessions.get(i).getId());
            mainFrame.getMainSessionPanel().getSessionPanelForTab(i).isInfoPanel();
            ArrayList<Team> moreTeams = client.getTeamInfoToSession(sessions.get(i).getId());
            for (int j = 0; j < moreTeams.size(); j++) {
                ArrayList<User> users = client.getUsersToTeam(moreTeams.get(j).getId());
                TeamSessionInfoPanel infoPanl = new TeamSessionInfoPanel();
                infoPanl.isInfoPanel();

                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).addTeamTab(infoPanl, moreTeams.get(j).getName());
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getGoalForTeamTextArea().setText(moreTeams.get(j).getGoal());

                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getDeliveryTeamTextArea().setText(moreTeams.get(j).getDelivery());
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getTeamMemberList().addListSelectionListener(stmlsl);
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getUserRoles().clear();
                for (int k = 0; k < users.size(); k++) {
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getTeamMemberListModel().addElement(users.get(k).getFullname());
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getUsers().add(users.get(k));
                }
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).updateUserRoles(client, sessions.get(i).getId(),teams.get(j).getId());
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getFacilitatorCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getSecretaryCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getCustomerCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                if (j == 0) {
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getFacilitatorCheckBox().setVisible(true);
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getSecretaryCheckBox().setVisible(true);
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getCustomerCheckBox().setVisible(true);
                } else {

                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getFacilitatorCheckBox().setVisible(false);
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getSecretaryCheckBox().setVisible(false);
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j).getCustomerCheckBox().setVisible(false);

                }
            }
        }

    }
    /**
     * A method that goes through the users projects and sessions and finds the nearest session to date. Then shows the information for that
     * session on the welcome tab panel.
     */
    public void welcomeTabInsertData() {
        ArrayList<String> roles;

        if (!client.getAllSessionsForAllProjects().isEmpty()) {
            Session session = client.findNearestSession();
            if (session.getId() > 0) {
                String projectName = "";
                roles = client.getRoleToUserSession(client.getUserToUsername(client.getLoginn().getUsername()).getId(), session.getId());
                System.out.println("hello " + roles.size());
                for (int i = 0; i < client.getAllProjects().size(); i++) {
                    if (client.getAllProjects().get(i).getId() == session.getProjectId()) {
                        projectName = client.getAllProjects().get(i).getName();
                        // roles = client.getRoleToUserProject(, session.getProjectId());

                    }
                }
                welcomeTabPanel.setSessionInfo(userName, session.getDate(), session.getName(), projectName, session.getPreparation(), roles);
                for (int i = 0; i < roles.size(); i++) {
                    System.out.println(roles.get(i));
                    if (roles.get(i).equals("Fasilitator")) {
                        Calendar currenDate = Calendar.getInstance();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dato = dateFormat.format(currenDate.getTime());
                        int todaysdate = Integer.parseInt(dato.replaceAll("-", ""));
                        dato = session.getDate();
                        int sessionDate = Integer.parseInt(dato.replaceAll("-", ""));
                        System.out.println(todaysdate);
                        System.out.println(sessionDate);
                        if (todaysdate == sessionDate) {
                            System.out.println("test");
                            mainFrame.getMainSessionPanel().getNewCountdownButton().setEnabled(true);
                            mainFrame.getMainSessionPanel().getStopCountdownButton().setEnabled(true);
                            mainFrame.getMainSessionPanel().getAddMeButton().setText("Fjern");
                            mainFrame.getMainSessionPanel().getRemoveMeButton().setText("Fjern alle");
                        }
                    }
                }

            } else {
                welcomeTabPanel.hideSessionInfo(userName);
            }
        } else {
            welcomeTabPanel.hideSessionInfo(userName);
        }
    }

    /**
     * A method that updates the userlist frame.
     */
    public void updateUserlistFrame() {
        userlistFrame.getUserlistModel().clear();
        allUsers = client.getAllUsers();

        for (User u : allUsers) {
            if (!u.getUsername().equals(userName)) {
                userlistFrame.getUserlistModel().addElement(u.getFullname());
            }
        }
    }

    public void setUpUserAdminMenu(){
        if(client.isAdmin()){
        JMenuItem newUserItem = new JMenuItem("Ny bruker");
            newUserItem.addActionListener(new userMenuActionListener());
            mainFrame.getUserAdministrationMenu().add(newUserItem);
            JMenuItem userlistMenu = new JMenuItem("Brukerliste");
            userlistMenu.addActionListener(new userMenuActionListener());
            mainFrame.getUserAdministrationMenu().addSeparator();
            mainFrame.getUserAdministrationMenu().add(userlistMenu);
        }
        JMenuItem editUserItem = new JMenuItem("Endre egen brukerinformasjon");
        editUserItem.addActionListener(new userMenuActionListener());
        mainFrame.getUserAdministrationMenu().add(editUserItem);
    }

    /**
     * A method that updates the project list on the projectmenu.
     */
    public void updateProjectList() {
        JMenuItem projectItem;
        mainFrame.getProjectMenu().removeAll();

        if(client.isAdmin()){
            JMenuItem newProjectItem = new JMenuItem("Nytt prosjekt");
            newProjectItem.addActionListener(new MenuActionListener());
            mainFrame.getProjectMenu().add(newProjectItem);
            

        }//
        JMenu subProjectMenu = new JMenu("Prosjekter");
        mainFrame.getProjectMenu().addSeparator();
        mainFrame.getProjectMenu().add(subProjectMenu);
        if (!client.getProjectNames().isEmpty()) {
            for (int i = 0; i < client.getAllProjects().size(); i++) {
                projectItem = new JMenuItem(client.getAllProjects().get(i).getName());
                projectItem.addActionListener(new MenuActionListener());
                projectItem.setActionCommand(Integer.toString(client.getAllProjects().get(i).getId()));
                subProjectMenu.add(projectItem);
            }
        }
        JMenuItem projectInfo = new JMenuItem("Vis prosjektinformasjon");
        projectInfo.addActionListener(new MenuActionListener());
        JMenuItem actionList = new JMenuItem("Aksjonsliste");
        JMenuItem decisionList = new JMenuItem("Beslutningsliste");
        decisionList.addActionListener(new MenuActionListener());
        actionList.addActionListener(new MenuActionListener());
        mainFrame.getProjectMenu().add(decisionList);
        mainFrame.getProjectMenu().add(actionList);
        mainFrame.getProjectMenu().addSeparator();
        mainFrame.getProjectMenu().add(projectInfo);
    }
    /**
     * A method that shows the userlist frame.
     */
    public void showUserList() {
        ArrayList<User> users = client.getAllUsers();
        userlistFrame.getUserlistModel().clear();

        for (User u : users) {
            if (!u.getUsername().equals(userName)) {
                userlistFrame.getUserlistModel().addElement(u.getFullname());
            }
        }
        userlistFrame.setVisible(true);
        userlistFrame.saveButtonClicked("", "", "");
    }

    /**
     * A method that shows an error message when theres no connection to the server.
     */
    public void serverConnectionError() {
        loginFrame.getLoginButton().setEnabled(false);
        loginFrame.getUserNameInput().setFocusable(false);
        loginFrame.getjPasswordField().setFocusable(false);
        loginFrame.getErrorMessageLabel().setText("Kunne ikke kontakte server.");
        loginFrame.getErrorMessageLabel().setVisible(true);
    }

    /*
     * Getters and setters
     */
    public ActivityInfoPanel getActivityInfoPanel() {
        return activityInfoPanel;
    }

    public ActivityListPanel getActivityListPanel() {
        return activityListPanel;
    }

    public CalendarFrame getCalendarFrame() {
        return calendarFrame;
    }


    public ChatPanel getChatPanel() {
        return chatPanel;
    }


    public Client getClient() {
        return client;
    }

    public LoginFrame getLoginFrame() {
        return loginFrame;
    }

    public MainFrame getMainFrame() {
        return mainFrame;
    }

    public MainSessionPanel getMainPanel() {
        return mainSessionPanel;
    }

    public NewProjectFrame getNewProjectFrame() {
        return newProjectFrame;
    }

    public ProjectInfoPanel getProjectInfoPanel() {
        return projectInfoPanel;
    }

    public SessionPanelForTabbedPane getSessionPanel() {
        return sessionPanel;
    }

    public AddUserFrame getAddUserFrame() {
        return addUserFrame;
    }

    public AddUsersToProjectFrame getAddUsersToProjectFrame() {
        return addUsersToProjectFrame;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    /*
     * The listener classes.
     */

    private class CloseUserListFrameListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            userlistFrame.setVisible(false);
        }
    }

    private class EditUserInfoListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String text = source.getText();
            User selectedUser = null;
            String username = "";
            String workplace = "";
            String expertise = "";
            int index = 0;
            if (text.equals("Rediger")) {
                if (!userlistFrame.getUserlistJList().isSelectionEmpty()) {
                    userlistFrame.editButtonClicked();

                }
            } else {
                if (!userlistFrame.getUserlistJList().isSelectionEmpty()) {

                    username = userlistFrame.getUserNameTextField().getText();
                    workplace = userlistFrame.getWorkplaceTextArea().getText();
                    expertise = userlistFrame.getExpertiseTextArea().getText();
                    userlistFrame.saveButtonClicked(username, workplace, expertise);
                    userlistFrame.setSelectedUsername(username);
                    index = userlistFrame.getUserlistJList().getSelectedIndex();

                    for (User u : allUsers) {
                        if (userlistFrame.getUserlistJList().getSelectedValue().equals(u.getFullname())) {
                            selectedUser = u;
                            break;
                        }
                    }
                    client.editUserInfo(selectedUser, username, expertise, workplace);
                    userlistFrame.getUserNameTextField().setText(username);
                    userlistFrame.getWorkplaceTextArea().setText(workplace);
                    userlistFrame.getExpertiseTextArea().setText(expertise);
                    updateUserlistFrame();

                    userlistFrame.setSelectedIndexUserList(index);

                }

            }
        }
    }

    private class AddUsersToProjectActionListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String text = source.getText();
            if (text.equals("Legg til brukere")) {
                showAddedUsersFrame(text);
            } else {

                showAddedUsersFrame(text);
            }

        }
    }

    private class AddResourceActionListener implements ActionListener {

        String selectedValue;

        public void actionPerformed(ActionEvent ae) {
            if (!resourceToProjectFrame.getAvailableResouceList().isSelectionEmpty()) {
                selectedValue = (String) resourceToProjectFrame.getAvailableResouceList().getSelectedValue();
                int index = resourceToProjectFrame.getAvailableResouceList().getSelectedIndex();
                for (int i = 0; i < resourceToProjectFrame.getAvailableResourceListModel().size(); i++) {
                    if (resourceToProjectFrame.getAvailableResourceListModel().get(i).equals(selectedValue)) {
                        //This is a check to find out if the resource is free on the selected date
                        String fromDate = resourceToProjectFrame.getFromeDateTextField().getText();
                        String toDate = resourceToProjectFrame.getToDateTextField().getText();
                        if (fromDate.length() == 10 && toDate.length() == 10) {
                            String text = client.registerResourceToProject(new ResourceProject(
                                    resourceToProjectFrame.getAvailableResources().get(index),
                                    resourceToProjectFrame.getFromeDateTextField().getText(),
                                    resourceToProjectFrame.getToDateTextField().getText(),
                                    client.getSelectedProject().getId()));
                            if (text.length() < 5) {
                                resourceToProjectFrame.getSelectedResourceListModel().addElement(selectedValue);
                                resourceToProjectFrame.getSelectedResources().add(resourceToProjectFrame.getAvailableResources().get(index));
                                resourceToProjectFrame.getAvailableResourceListModel().removeElementAt(i);
                                resourceToProjectFrame.getResourceProject().add(new ResourceProject(
                                        resourceToProjectFrame.getAvailableResources().get(index),
                                        resourceToProjectFrame.getFromeDateTextField().getText(),
                                        resourceToProjectFrame.getToDateTextField().getText(),
                                        client.getSelectedProject().getId()));
                                resourceToProjectFrame.getAvailableResources().remove(index);
                            } else {
                                JOptionPane.showMessageDialog(null, "Valgt " + text);

                            }
                        } else {
                            JOptionPane.showMessageDialog(null, "Vennligst velg datointervall");
                        }


                    }
                }
            }
        }
    }

    private class NewResourceActionListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            try {
                ArrayList<ResourceType> types = client.getAllResourceTypes();
                if (types.size() > 0) {
                    for (int i = 0; i < types.size(); i++) {
                        resourceFrame.getResourceTypeComboModel().addElement(types.get(i).getType());
                    }
                } else {
                    resourceFrame.getResourceTypeBox().setVisible(false);
                    resourceFrame.getResourceTypeTextField().setVisible(true);
                }
            } catch (RemoteException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            resourceFrame.setVisible(true);
        }
    }

    private class RemoteResourceActionListener implements ActionListener {

        String selectedValue;

        public void actionPerformed(ActionEvent ae) {
            if (!resourceToProjectFrame.getSelectedResourcesList().isSelectionEmpty()) {
                selectedValue = (String) resourceToProjectFrame.getSelectedResourcesList().getSelectedValue();
                int index = resourceToProjectFrame.getSelectedResourcesList().getSelectedIndex();
                for (int i = 0; i < resourceToProjectFrame.getSelectedResourceListModel().size(); i++) {
                    if (resourceToProjectFrame.getSelectedResourceListModel().get(i).equals(selectedValue)) {

                        resourceToProjectFrame.getSelectedResourceListModel().removeElementAt(i);
                        resourceToProjectFrame.getAvailableResourceListModel().addElement(selectedValue);
                        resourceToProjectFrame.getAvailableResources().add(resourceToProjectFrame.getSelectedResources().get(index));
                        client.deleteResourceToProject(client.getSelectedProject().getId(),
                                resourceToProjectFrame.getSelectedResources().get(index).getId());
                        resourceToProjectFrame.getSelectedResources().remove(index);
                        resourceToProjectFrame.getResourceProject().remove(index);
                    }
                }
            }
        }
    }

    private class SaveResourceActionListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            resourceToProjectFrame.setVisible(false);
            client.sendResourceUpdates();
        }
    }

    private class AddUserToProjectButton implements ActionListener {

        String selectedValue;

        public void actionPerformed(ActionEvent e) {
            if (addUsersToProjectFrame.getTeamInfoPanels().size() < 1) {
                newTeam();
                addUsersToProjectFrame.getTeamInfoPanels().get(0).getFasilitatorCheckBox().setVisible(true);
                addUsersToProjectFrame.getTeamInfoPanels().get(0).getCustomerCheckBox().setVisible(true);
                addUsersToProjectFrame.getTeamInfoPanels().get(0).getSecretaryCheckBox().setVisible(true);
            }
            if (!addUsersToProjectFrame.getUsersList().isSelectionEmpty()) {
                selectedValue = (String) addUsersToProjectFrame.getUsersList().getSelectedValue();
                int index = addUsersToProjectFrame.getUsersList().getSelectedIndex();
                for (int i = 0; i < addUsersToProjectFrame.getUsersListModel().size(); i++) {
                    if (addUsersToProjectFrame.getUsersListModel().get(i).equals(selectedValue)) {


                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                                getTeamMemberListModel().addElement(selectedValue);

                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getUsers().add(addUsersToProjectFrame.getUsers().get(index));
                        if (addUsersToProjectFrame.getSelectedTeam() == 0) {
                            addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                                    getUserRoles().add(new addUserRoles(addUsersToProjectFrame.getUsers().get(index)));
                        }
                        addUsersToProjectFrame.getUsersListModel().removeElementAt(i);
                        addUsersToProjectFrame.getUsers().remove(index);
                        break;
                    }
                }
            }
        }
    }

    private class NewTeamButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            newTeam();
        }
    }

    private class CloseAddUsersToProjectFrameListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {

            addUsersToProjectFrame.setVisible(false);
            //Need to adduser to jlist
            newProjectFrame.getProjectInfoPanel().getAddedUserListModel().removeAllElements();
            for (int i = 0; i < addUsersToProjectFrame.getTeamInfoPanels().size(); i++) {
                for (int j = 0; j < addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().size(); j++) {
                    newProjectFrame.getProjectInfoPanel().getAddedUserListModel().addElement(
                            addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().get(j).getFullname());
                }
            }
        }
    }

    private class AddNewUserListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            addUserFrame.setVisible(true);

        }
    }

    private class CloseEditUserFrameListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            editUserFrame.setVisible(false);
        }
    }

    private class RemoteUserFromProjectListener implements ActionListener {

        String selectedValue;

        public void actionPerformed(ActionEvent e) {


            if (!addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getTeamMembersList().isSelectionEmpty()) {
                selectedValue = (String) addUsersToProjectFrame.getTeamInfoPanels().get(
                        addUsersToProjectFrame.getSelectedTeam()).getTeamMembersList().getSelectedValue();
                int index = addUsersToProjectFrame.getTeamInfoPanels().get(
                        addUsersToProjectFrame.getSelectedTeam()).getTeamMembersList().getSelectedIndex();
                for (int i = 0; i < addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                        getTeamMemberListModel().size(); i++) {
                    if (addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                            getTeamMemberListModel().get(i).equals(selectedValue)) {
                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                                getTeamMemberListModel().removeElementAt(i);
                        User u = addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                                getUsers().get(index);
                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                                getUsers().remove(index);
                        addUsersToProjectFrame.getUsersListModel().addElement(selectedValue);
                        addUsersToProjectFrame.getUsers().add(u);
                        break;
                    }
                }
            }
        }
    }

    private class UpdateUserActionListener implements ActionListener {

        ArrayList<String> rolles = new ArrayList<String>();

        public void actionPerformed(ActionEvent ae) {
            String oldPassword = "", newPassword = "", confirmedPassword = "", username = "", fullname = "", workplace = "",
                    expertise = "";
            boolean registredNewPassword = true;
            boolean proseed = false;
            char[] passChar = editUserFrame.getNewPasswordField().getPassword();
            for (int i = 0; i < passChar.length; i++) {
                newPassword += "" + passChar[i];
            }
            passChar = editUserFrame.getConfirmedPasswordField().getPassword();
            for (int i = 0; i < passChar.length; i++) {
                confirmedPassword += "" + passChar[i];
            }
            passChar = editUserFrame.getOldPasswordField().getPassword();
            for (int i = 0; i < passChar.length; i++) {
                oldPassword += "" + passChar[i];
            }
            if (newPassword.trim().equals("") && oldPassword.trim().equals("") && confirmedPassword.trim().equals("")) {
                registredNewPassword = false;
                proseed = true;
            } else if (!newPassword.equals(confirmedPassword)) {
                JOptionPane.showMessageDialog(null, "Nytt passord er ikke likt");
            } else if (newPassword.length() < 6) {
                JOptionPane.showMessageDialog(null, "Passord må være minst 6 tegn");

            } else if (!client.isCorrectPassword(oldPassword, client.getLoginn().getUsername())) {
                JOptionPane.showMessageDialog(null, "Gammelt passord er ikke riktig");
            }
            if (proseed) {
                username = editUserFrame.getEpostField().getText();
                fullname = editUserFrame.getFullnameField().getText();
                workplace = editUserFrame.getWorkplaceField().getText();
                expertise = editUserFrame.getEkspertiseField().getText();
                if (editUserFrame.getProjectLeaderCheckBox().isSelected()) {
                    rolles.add("Prosjektleder");
                }
                if (editUserFrame.getFasilitatorCheckBox().isSelected()) {
                    rolles.add("Fasilitator");
                }
                if (editUserFrame.getSecretaryCheckBox().isSelected()) {
                    rolles.add("Sekretær");
                }
                User u = client.getUserToUsername(client.getLoginn().getUsername());
                int i = u.getId();
                if (registredNewPassword) {
                    u = new User(i, username, newPassword, workplace, fullname, expertise);
                    client.editUser(u, rolles);
                    rolles.clear();
                } else {
                    u = new User(i, username, u.getPassword(), workplace, fullname, expertise);
                    client.editUser(u, rolles);
                }
                rolles.clear();
                JOptionPane.showMessageDialog(null, "Brukerinfo oppdatert");
            }
        }
    }

    private class ChatSendButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            client.sendMessage(chatPanel.getInputText().getText().trim());
            chatPanel.getInputText().setText("");
            chatPanel.getInputText().requestFocus();
            chatPanel.getInputText().setCaretPosition(0);

        }
    }

    private class NewActivityButtonClickedListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            activityInfoPanel.clearInput();
            activityInfoPanel.setVisible(true);
            activityListPanel.getActivityJList().clearSelection();
            activityListPanel.getActivityJList().setEnabled(false);
            activityListPanel.getDeleteActivityButton().setText("Avbryt");
            for (int i = 0; i < client.getProjectUsers().size(); i++) {
                activityInfoPanel.getActivityResponsibleModel().addElement(client.getProjectUsers().get(i).getFullname());
            }
            for (int i = 0; i < client.getNumberOfSessions(); i++) {
                activityInfoPanel.getBoundToSessionModel().addElement(client.getSessions().get(i).getName());
            }
            activityInfoPanel.getStartDateTextField().addMouseListener(tfcl);
            activityInfoPanel.getEndDateTextField().addMouseListener(tfcl);
            activityInfoPanel.getActivityNameTextField().setFocusable(true);
        }
    }

    private class VoiceListButtonListener implements ActionListener {

        JButton source;
        String text;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            text = source.getText();
            if (text.equals("Legg meg til")) {
                User u = client.getUserToUsername(client.getLoginn().getUsername());
                client.insertIntoVoiceList(client.getSelectedProject().getId(), u.getId());
                updateVoiceList();
                client.sendVoiceListUpdate();
            } else if (text.equals("Fjern meg")) {
                User u = client.getUserToUsername(client.getLoginn().getUsername());
                client.removeFromVoiceList(client.getSelectedProject().getId(), u.getId());
                updateVoiceList();
                client.sendVoiceListUpdate();
            } else if (text.equals("Fjern alle")) {
                client.removeVoiceList(client.getSelectedProject().getId());
                updateVoiceList();
                client.sendVoiceListUpdate();
            } else if (text.equals("Fjern")) {
                if (!mainFrame.getMainSessionPanel().getVoiceList().isSelectionEmpty()) {
                    String name = (String) mainFrame.getMainSessionPanel().getVoiceList().getSelectedValue();
                    ArrayList<User> users = client.getProjectUsers();
                    for (int i = 0; i < users.size(); i++) {
                        if (users.get(i).getFullname().equals(name)) {
                            client.removeFromVoiceList(client.getSelectedProject().getId(), users.get(i).getId());
                            mainFrame.getMainSessionPanel().getVoiceListModel().removeElement(name);
                            break;
                        }
                    }
                }
                updateVoiceList();
                client.sendVoiceListUpdate();
            }

        }
    }

    private class AvailableResourcesListSelectionListenener extends MouseAdapter {

        JList source;
        String text;

        public void mouseClicked(MouseEvent me) {
            resourceToProjectFrame.getFromeDateTextField().setText("");
            resourceToProjectFrame.getToDateTextField().setText("");
        }
    }

    private class AddedResourcesListSelectionListener extends MouseAdapter {

        String selectedResource;
        ResourceProject resource;

        public void mouseClicked(MouseEvent me) {
            selectedResource = (String) resourceToProjectFrame.getSelectedResourcesList().getSelectedValue();
            for (int i = 0; i < client.getAllResourceToProject(client.getSelectedProject().getId()).size(); i++) {
                String resourceName = client.getAllResourceToProject(client.getSelectedProject().getId()).get(i).getResource().getName();
                if (resourceName.equals(selectedResource)) {
                    resource = client.getAllResourceToProject(client.getSelectedProject().getId()).get(i);

                    resourceToProjectFrame.getFromeDateTextField().setText(resource.getFromdate());
                    resourceToProjectFrame.getToDateTextField().setText(resource.getToDate());
                }
            }

        }
    }

    private class TeamSessionInfoPanelButtonListener implements ActionListener {

        JCheckBox source;
        String text;

        public void actionPerformed(ActionEvent ae) {
            source = (JCheckBox) ae.getSource();
            text = source.getText();
            if (!mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(0).getTeamMemberList().isSelectionEmpty()) {
                int index = mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(mainFrame.getMainSessionPanel().getSelectedSessionPanel().getExpertGroupsTabbedPane().getSelectedIndex()).getIndexUserRoles((String) mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(0).getTeamMemberList().getSelectedValue());

                if (text.equals("Fasilitator")) {
                    mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(mainFrame.getMainSessionPanel().getSelectedSessionPanel().getSelectedTeam()).getUserRoles().get(index).setFasilitator(source.isSelected());
                } else if (text.equals("Sekretær")) {
                    mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(mainFrame.getMainSessionPanel().getSelectedSessionPanel().getSelectedTeam()).getUserRoles().get(index).setSecretary(source.isSelected());
                } else if (text.equals("Kunde")) {
                    mainFrame.getMainSessionPanel().getSelectedSessionPanel().getTeamSessionInfoPanels().get(mainFrame.getMainSessionPanel().getSelectedSessionPanel().getSelectedTeam()).getUserRoles().get(index).setCustomer(source.isSelected());
                }
            }
        }
    }

    private class TeamInfoPanelButtonListener implements ActionListener {

        JCheckBox source;
        String text;

        public void actionPerformed(ActionEvent ae) {
            source = (JCheckBox) ae.getSource();
            text = source.getText();
            int selectedUser = addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getTeamMembersList().getSelectedIndex();
            if (selectedUser > 0) {
                int index = addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getIndexUserRoles(
                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getSelectedUser());
                if (text.equals("Fasilitator")) {
                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).
                            setFasilitator(source.isSelected());
                } else if (text.equals("Sekretær")) {
                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).
                            setSecretary(source.isSelected());
                } else if (text.equals("Kunde")) {
                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).setCustomer(source.isSelected());
                }
            }
        }
    }

    private class TeamMemberListSelectionListener implements ListSelectionListener {

        String selectedU = "";
        String lastSelectedU = "";
        int mod = 0;

        public void valueChanged(ListSelectionEvent e) {
            selectedU = (String) addUsersToProjectFrame.getTeamInfoPanels().
                    get(addUsersToProjectFrame.getSelectedTeam()).getTeamMembersList().getSelectedValue();
            if (mod % 2 == 0) {
                addUsersToProjectFrame.getTeamInfoPanels().
                        get(addUsersToProjectFrame.getSelectedTeam()).setSelectedUser(selectedU);
                int index = addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).getIndexUserRoles(
                        addUsersToProjectFrame.getTeamInfoPanels().
                        get(addUsersToProjectFrame.getSelectedTeam()).getSelectedUser());
                if (index > -1) {
                    ArrayList<addUserRoles> temp = addUsersToProjectFrame.getTeamInfoPanels().get(0).getUserRoles();

                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                            getFasilitatorCheckBox().setSelected(addUsersToProjectFrame.getTeamInfoPanels().
                            get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).isFasilitator());

                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                            getSecretaryCheckBox().setSelected(addUsersToProjectFrame.getTeamInfoPanels().
                            get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).isSecretary());

                    addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getSelectedTeam()).
                            getCustomerCheckBox().setSelected(addUsersToProjectFrame.getTeamInfoPanels().
                            get(addUsersToProjectFrame.getSelectedTeam()).getUserRoles().get(index).isCustomer());

                }
            }
            mod++;
        }
    }

    private class UserlistFrameListSelectionListener extends MouseAdapter {

        String selectedU = "";
        int mod = 0;
        User selectedUser;
        int selectedIndex;

        public void mouseClicked(MouseEvent me) {
            if (!userlistFrame.getUserlistJList().isSelectionEmpty()) {
                selectedU = (String) userlistFrame.getUserlistJList().getSelectedValue();
                for (User u : allUsers) {
                    if (u.getFullname().equals(selectedU)) {
                        selectedUser = u;
                        break;
                    }
                }
                userlistFrame.getUserNameTextField().setText(selectedUser.getFullname());
                userlistFrame.getExpertiseTextArea().setText(selectedUser.getExpertise());
                userlistFrame.getWorkplaceTextArea().setText(selectedUser.getWorkplace());

                selectedIndex = userlistFrame.getUserlistJList().getSelectedIndex();
                userlistFrame.setSelectedIndex(selectedIndex);
                userlistFrame.setSelectedUsername(selectedUser.getFullname());
            }
        }
    }

    private class ExpertiseListSelectionListener implements ListSelectionListener {

        String selectedU = "";

        public ExpertiseListSelectionListener() {
        }

        public void valueChanged(ListSelectionEvent e) {
            int index = addUsersToProjectFrame.getUsersList().getSelectedIndex();
            if (index > 0) {
                addUsersToProjectFrame.getUserExpertiseTextArea().setText(addUsersToProjectFrame.getUsers().get(index).getExpertise());
            } else {
                addUsersToProjectFrame.getUserExpertiseTextArea().setText("");
            }

        }
    }

    private class TeamTabListener implements ChangeListener {

        public void stateChanged(ChangeEvent ce) {
            JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
            if (sourceTabbedPane.getSelectedIndex() > 0) {
                addUsersToProjectFrame.setSelectedTeam(sourceTabbedPane.getSelectedIndex());
            } else {
                addUsersToProjectFrame.setSelectedTeam(0);
            }
        }
    }

    private class CreateUserActionListener implements ActionListener {

        String workplace;
        String fullname;
        String expertise;
        String epost;
        ArrayList<String> rolles = new ArrayList<String>();

        public void actionPerformed(ActionEvent ae) {

            workplace = addUserFrame.getWorkPlaceTextField().getText();
            fullname = addUserFrame.getFullNameTextField().getText();
            expertise = addUserFrame.getEkspertiseTextArea().getText();
            epost = addUserFrame.getEpostField().getText();

            if (workplace.trim().equals("") || fullname.trim().equals("") || epost.trim().equals("")) {

                JOptionPane.showMessageDialog(null, "Vennligst fyll inn navn,epost og arbeidsplass");

            } else {
                User u = client.createUser(workplace, fullname, expertise, epost);
                JOptionPane.showMessageDialog(null, "Bruker lagt til i systemet samt epost til brukeren sendt!.\n"
                        + "Brukernavn: " + u.getUsername()
                        + "\nPassord: " + u.getPassword());
                addUsersToProjectFrame.getUsersListModel().addElement(u.getFullname());
                addUsersToProjectFrame.getUsers().add(u);
                if (addUserFrame.getProjectLeaderCheckBox().isSelected()) {
                    rolles.add("Prosjekt Leder");
                }
                if (addUserFrame.getFasilitatotCheckBox().isSelected()) {
                    rolles.add("Fasilitator");
                }
                if (addUserFrame.getSecretaryCheckBox().isSelected()) {
                    rolles.add("Sekretær");
                }
                client.registerRolesToUser(u.getId(), rolles);
                updateUserlistFrame();
                client.sendUserUpdates();
            }
        }
    }

    private class SaveSessionButtonListener implements ActionListener {

        String sessionName;
        String dato;
        String place;
        String startTime;
        String endTime;
        String teamGoal;
        String teamDelivery;
        String evaluation;
        String preparation;

        public void actionPerformed(ActionEvent ae) {
            JButton source = (JButton) ae.getSource();
            boolean date = true;
            boolean name = true;
            boolean time = true;
            if (source.getText().equals("Rediger")) {
                if (!client.isAdmin()) {
                    ArrayList<Team> teams = client.getTeamsToProject(client.getSelectedProject().getId());
                    int teamnumber = -1;
                    for (int j = 0; j < teams.size(); j++) {
                        ArrayList<User> users = client.getUsersToTeam(teams.get(j).getId());
                        for (int k = 0; k < users.size(); k++) {
                            if (users.get(k).getId() == client.getUserToUsername(client.getLoginn().getUsername()).getId()) {
                                teamnumber = j;
                            }
                        }
                    }
                    if(teamnumber==0){
                        for (int i = 0; i < mainSessionPanel.getSessionPanels().size(); i++) {
                            mainSessionPanel.getSessionPanelForTab(i).editButtonClicked();
                            mainSessionPanel.getSessionPanelForTab(i).getSessionDateTextField().addMouseListener(tfcl);
                            mainSessionPanel.getAddNewSessionButton().setEnabled(true);
                            mainSessionPanel.getRemoveSessionButton().setEnabled(true);
                            mainSessionPanel.getCreateSessionPlanButton().setEnabled(true);
                        }
                    }else{
                        for(int i=0; i<mainSessionPanel.getSessionPanels().size();i++){
                            mainSessionPanel.getSessionPanels().get(i).getTeamInfoPanel(teamnumber).getGoalForTeamTextArea().setFocusable(true);
                            mainSessionPanel.getSessionPanels().get(i).getTeamInfoPanel(teamnumber).getDeliveryTeamTextArea().setFocusable(true);
                        }
                    }
                } else {
                    for (int i = 0; i < mainSessionPanel.getSessionPanels().size(); i++) {
                        mainSessionPanel.getSessionPanelForTab(i).editButtonClicked();
                        mainSessionPanel.getSessionPanelForTab(i).getSessionDateTextField().addMouseListener(tfcl);
                    }
                }
                if(!mainFrame.getMainSessionPanel().getSessionPanels().isEmpty())mainFrame.getMainSessionPanel().getEditSessionButton().setText("Lagre");

            } else {
                //Denne må sjekke først om det er en ny sesjons eller ikke, kan kansje bruke ArrayList<Session>?
                mainSessionPanel.getSessionPanelForTab(client.getSelectedSessionTab()).saveButtonClicked();
                int projectId = client.getSelectedProject().getId();
                client.updateSessionList();
                ArrayList<Session> sessions = client.getSessions();

                //Ingen lagrede sessjon, men vi ska lagre vår første nå
                if (sessions.isEmpty()) {
                    sessionName = mainSessionPanel.getSessionPanelForTab(0).getSessionName();
                    dato = mainSessionPanel.getSessionPanelForTab(0).getSessionDate();
                    startTime = mainSessionPanel.getSessionPanelForTab(0).getSessionTimeFrome().trim();
                    endTime = mainSessionPanel.getSessionPanelForTab(0).getSessionTimeTo().trim();
                    evaluation = mainSessionPanel.getSessionPanelForTab(0).getSessionEvaluation();
                    place = (String) mainSessionPanel.getSessionPanelForTab(0).getSessionPlaceModel().getSelectedItem();
                    preparation = mainSessionPanel.getSessionPanelForTab(0).getSessionPreparationTextArea().getText();
                    if (client.validateDate(dato)) {
                        if (!sessionName.trim().equals("")) {
                            if (client.validateTime(startTime) && client.validateTime(endTime)) {
                                int sessionId = client.createSession(projectId, sessionName, dato, place, startTime, endTime, evaluation, preparation);
                                mainFrame.getMainSessionPanel().getSessionPanelForTab(0).setSessionId(sessionId);
                                for (int i = 0; i < teams.size(); i++) {
                                    teamGoal = mainSessionPanel.getSessionPanelForTab(0).getTeamInfoPanel(i).getGoalForTeamTextArea().getText();
                                    teamDelivery = teamGoal = mainSessionPanel.getSessionPanelForTab(0).
                                            getTeamInfoPanel(i).getDeliveryTeamTextArea().getText();
                                    client.createteamSession(teams.get(i).getId(), sessionId, teamGoal, teamDelivery);
                                }
                                client.updateSessionList();
                                sessions = client.getSessions();
                            }else{
                                time=false;
                                JOptionPane.showMessageDialog(null, "Vennligst skriv inn tidspunkt.\nF.eks 1800");
                            }
                        } else {
                            name = false;
                            JOptionPane.showMessageDialog(null, "Vennligst skriv inn navn på sesjon.");
                        }
                    } else {
                        date = false;

                        JOptionPane.showMessageDialog(null, "Vennligst velg dato.");
                    }

                } else {
                    for (int j = 0; j < mainFrame.getMainSessionPanel().getSessionPanels().size(); j++) {
                        if (mainFrame.getMainSessionPanel().getSessionPanels().get(j).getSessionId() > 0) {
                            int sessionId = mainFrame.getMainSessionPanel().getSessionPanels().get(j).getSessionId();
                            sessionName = mainSessionPanel.getSessionPanelForTab(j).getSessionName();
                            dato = mainSessionPanel.getSessionPanelForTab(j).getSessionDate();
                            startTime = mainSessionPanel.getSessionPanelForTab(j).getSessionTimeFrome();
                            endTime = mainSessionPanel.getSessionPanelForTab(j).getSessionTimeTo();
                            evaluation = mainSessionPanel.getSessionPanelForTab(j).getSessionEvaluation();
                            place = (String) mainSessionPanel.getSessionPanelForTab(j).getSessionPlaceModel().getSelectedItem();
                            preparation = mainSessionPanel.getSessionPanelForTab(j).getSessionPreparationTextArea().getText();
                            mainFrame.getMainSessionPanel().getSessionPanelForTab(j).setSessionId(sessionId);

                            if (client.validateDate(dato)) {
                                if (!sessionName.trim().equals("")) {
                                    if (client.validateTime(startTime) && client.validateTime(endTime)) {
                                    client.editSession(new Session(sessionId, projectId, sessionName, dato, place, startTime, endTime, evaluation, preparation));
                                    for (int i = 0; i < teams.size(); i++) {
                                        teamGoal = mainSessionPanel.getSessionPanels().get(j).getTeamInfoPanel(i).getGoalForTeamTextArea().getText();
                                        teamDelivery = teamGoal = mainSessionPanel.getSessionPanelForTab(j).
                                                getTeamInfoPanel(i).getDeliveryTeamTextArea().getText();
                                        client.editTeamSession(teams.get(i).getId(), sessionId, teamGoal, teamDelivery);
                                    }
                                    }else{
                                        time=false;
                                        JOptionPane.showMessageDialog(null, "Vennligst skriv inn tidspunkt.\nF.eks 1800");
                                    }
                                } else {
                                    JOptionPane.showMessageDialog(null, "Vennligst skriv inn navn");
                                    name = false;
                                }

                            } else {
                                date = false;
                                JOptionPane.showMessageDialog(null, "Vennligst skriv inn dato.");
                            }

                        } else {
                            sessions.add(new Session());
                            sessionName = mainSessionPanel.getSessionPanelForTab(j).getSessionName();
                            dato = mainSessionPanel.getSessionPanelForTab(j).getSessionDate();
                            startTime = mainSessionPanel.getSessionPanelForTab(j).getSessionTimeFrome();
                            endTime = mainSessionPanel.getSessionPanelForTab(j).getSessionTimeTo();
                            evaluation = mainSessionPanel.getSessionPanelForTab(j).getSessionEvaluation();
                            place = (String) mainSessionPanel.getSessionPanelForTab(j).getSessionPlaceModel().getSelectedItem();
                            preparation = mainSessionPanel.getSessionPanelForTab(j).getSessionPreparationTextArea().getText();
                            if (client.validateDate(dato)) {
                                if (!sessionName.trim().equals("")) {
                                    if (client.validateTime(startTime) && client.validateTime(endTime)) {
                                        int sessionId = client.createSession(projectId, sessionName, dato, place, startTime, endTime, evaluation, preparation);
                                        mainFrame.getMainSessionPanel().getSelectedSessionPanel().setSessionId(sessionId);
                                        for (int i = 0; i < teams.size(); i++) {
                                            teamGoal = mainSessionPanel.getSessionPanelForTab(j).getTeamInfoPanel(i).getGoalForTeamTextArea().getText();

                                            teamDelivery = teamGoal = mainSessionPanel.getSessionPanelForTab(j).
                                                    getTeamInfoPanel(i).getDeliveryTeamTextArea().getText();

                                            client.createteamSession(teams.get(i).getId(), sessionId, teamGoal, teamDelivery);
                                        }
                                    }else{
                                        time=false;
                                        JOptionPane.showMessageDialog(null, "Vennligst skriv inn tidspunkt.\nF.eks 1800");
                                    }
                                } else {
                                    name = false;
                                    JOptionPane.showMessageDialog(null, "Vennligst skiv inn navn");
                                }


                            } else {
                                date = false;
                                JOptionPane.showMessageDialog(null, "Vennligst skriv inn dato.");
                            }

                        }
                    }
                }
                if (date && name && time) {
                    client.updateSessionList();
                    sessions = client.getSessions();
                    System.out.println("hvor mange sessjoner");
                    System.out.println(sessions.size());
                    //Sesjon er lagret, nå må brukerne lagres
                    ArrayList<User> facilitators = new ArrayList<User>();
                    ArrayList<User> secretaries = new ArrayList<User>();
                    ArrayList<User> customers = new ArrayList<User>();
                    ArrayList<User> experts = new ArrayList<User>();

                    Module.addUserRoles tempUserRole;
                    TeamSessionInfoPanel teamSessionInfoPanel;
                    teams = client.getTeamsToProject(client.getSelectedProject().getId());
                    //Sletter alle tidligere brukere til sesjone
                    for (int i = 0; i < sessions.size(); i++) {
                        client.removeUsersFromSession(sessions.get(i).getId());
                    }

                    //går igjennom antall sesjonspaneler
                    for (int i = 0; i < sessions.size(); i++) {
                        mainSessionPanel.getSessionPanelForTab(i).saveButtonClicked();
                        mainSessionPanel.getSessionPanelForTab(i).getSessionDateTextField().removeMouseListener(tfcl);
                        //går igjennom alle teampaneler for hvert sesjonspanel
                        for (int j = 0; j < teams.size(); j++) {
                            teamSessionInfoPanel = mainSessionPanel.getSessionPanelForTab(i).getTeamSessionInfoPanels().get(j);
                            int teamId = teams.get(j).getId();
                            int t = mainFrame.getMainSessionPanel().getSessionPanels().get(0).getTeamSessionInfoPanels().get(0).getUserRoles().size();
                            if (j == 0) {
                                for (int k = 0; k < teamSessionInfoPanel.getUserRoles().size(); k++) {
                                    tempUserRole = teamSessionInfoPanel.getUserRoles().get(k);
                                    
                                    if (tempUserRole.isFasilitator()) {
                                        facilitators.add(tempUserRole.getUser());
                                    }
                                    if (tempUserRole.isSecretary()) {
                                        secretaries.add(tempUserRole.getUser());
                                    }
                                    if (tempUserRole.isCustomer()) {
                                        customers.add(tempUserRole.getUser());
                                    }
                                    if (!tempUserRole.isSomething()) {
                                        experts.add(tempUserRole.getUser());
                                    }
                                }
                            } else {
                                for (int k = 0; k < teamSessionInfoPanel.getUsers().size(); k++) {
                                    System.out.println(teamSessionInfoPanel.getUsers().get(k).getFullname());
                                    experts.add(teamSessionInfoPanel.getUsers().get(k));
                                }
                            }

                            int sessionId = sessions.get(i).getId();
                            if (!experts.isEmpty()) {
                                client.registerUserToSession(sessionId, experts, 5, teamId);
                            }
                            if (!facilitators.isEmpty()) {
                                client.registerUserToSession(sessionId, facilitators, 2, teamId);
                            }
                            if (!secretaries.isEmpty()) {
                                client.registerUserToSession(sessionId, secretaries, 3, teamId);
                            }
                            if (!customers.isEmpty()) {
                                client.registerUserToSession(sessionId, customers, 4, teamId);
                            }
                            //mainFrame.getMainSessionPanel().getSessionPanels().get(i).getTeamSessionInfoPanels().get(j).updateUserRoles(client, sessionId);
                            facilitators.clear();
                            secretaries.clear();
                            customers.clear();
                            experts.clear();
                            client.updateSessionList();
                            mainFrame.getMainSessionPanel().getEditSessionButton().setText("Rediger");
                            welcomeTabInsertData();
                        }
                    }
                    client.sendSessionUpdates();

                } else {
                    mainSessionPanel.getSessionPanelForTab(client.getSelectedSessionTab()).editButtonClicked();
                }

            }

        }
    }

    private class SessionTeamMemberListSelectionListener implements ListSelectionListener {

        String selectedU;
        int selectedIndex;
        int selectedTeamIndex;
        int index;
        int mod = 0;

        public void valueChanged(ListSelectionEvent e) {

            selectedIndex = mainSessionPanel.getSessionsTabbedPane().getSelectedIndex();
            if (selectedIndex > -1) {
                selectedTeamIndex = mainSessionPanel.getSessionPanelForTab(selectedIndex).getExpertGroupsTabbedPane().getSelectedIndex();
                selectedU = (String) mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getTeamMemberList().getSelectedValue();
                if (mod % 2 == 0) {
                    mainFrame.getMainSessionPanel().getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).setSelectedUser(selectedU);
                    index = mainFrame.getMainSessionPanel().getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getIndexUserRoles(selectedU);

                    if (index > -1) {
                        mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getFacilitatorCheckBox().setSelected(mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getUserRoles().get(index).isFasilitator());
                        mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getSecretaryCheckBox().setSelected(mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getUserRoles().get(index).isSecretary());
                        mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getCustomerCheckBox().setSelected(mainSessionPanel.getSessionPanelForTab(selectedIndex).getTeamInfoPanel(selectedTeamIndex).getUserRoles().get(index).isCustomer());
                    }
                }
                mod++;
            }
        }
    }

    private class DecisionListButtonListener implements ActionListener {

        JButton source;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Ny beslutning")) {
                if (client.getSelectedProject().getId() > 0) {
                    addDecisionListItemFrame.clearInputt();
                    addDecisionListItemFrame.readyToRegister(client.getSessions(), client.getSelectedProject().getName());
                    addDecisionListItemFrame.setVisible(true);

                }
            }
            if (text.equals("Lukk")) {
                decisionListFrame.setVisible(false);

            }
            if (text.equals("Angre")) {
                decisionlist = client.getDecisionListToProject(client.getSelectedProject().getId());
                ArrayList<Session> sessions = client.getSessions();
                decisionListFrame.setTabel(decisionlist, sessions, client.getSelectedProject().getName());


            }
            if (text.equals("Lagre")) {
                if (client.getSelectedProject().getId() > 0) {
                    String intro = decisionListFrame.getIntroTextArea().getText();
                    
                    if(decisionListFrame.getDecisionListTable().isEditing()){
                            decisionListFrame.getDecisionListTable().getCellEditor().stopCellEditing();
                    }
                       
                    for (int i = 0; i < decisionlist.size(); i++) {
                        String value1 = (String) decisionListFrame.getDecisionListTable().getModel().getValueAt(i, 0);
                        String value2 = (String) decisionListFrame.getDecisionListTable().getModel().getValueAt(i, 1);
                        String value3 = (String) decisionListFrame.getDecisionListTable().getModel().getValueAt(i, 2);
                        System.out.println(value2);
                        int sessionId = 0;
                        for (int j = 0; j < client.getSessions().size(); j++) {
                            if (client.getSessions().get(j).getName().equals(value1)) {
                                sessionId = client.getSessions().get(j).getId();
                            }
                        }
                        decisionlist.get(i).setSessionId(sessionId);
                        decisionlist.get(i).setDescription(value2);
                        decisionlist.get(i).setStatus(value3);
                    }
                    client.editDecionListIntro(client.getSelectedProject().getId(), intro);
                    client.editDecisionList(decisionlist, client.getSelectedProject().getId());
                    client.sendDecisionListUpdates();
                    updateDecisionList();
                }
            }

        }
    }

    private class NewDecisionListItemButtonListener implements ActionListener {

        JButton source;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Lagre")) {
                int projectId = client.getSelectedProject().getId();
                int sessionId = 0;
                String sessionName = addDecisionListItemFrame.getSessionComboBox().getSelectedItem().toString();
                for (int j = 0; j < client.getSessions().size(); j++) {
                    if (client.getSessions().get(j).getName().equals(sessionName)) {
                        sessionId = client.getSessions().get(j).getId();
                    }
                }
                String description = addDecisionListItemFrame.getDecisionDescriptionTextArea().getText();
                if (!description.trim().equals("")) {
                    String status = addDecisionListItemFrame.getStatusComboBox().getSelectedItem().toString();
                    DecisionList d = new DecisionList(0, projectId, sessionId, description, status, "");
                    client.registerDecisionListItem(d);
                    //Må oppdatere decisionListen nå
                    updateDecisionList();
                    //decisionListFrame.getDecisionListTable().getModel().addTableModelListener(new DecisionListListener());
                    addDecisionListItemFrame.getDecisionDescriptionTextArea().setText("");
                    client.sendDecisionListUpdates();
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst skriv inn en beskrivelse");
                }

            }
            if (text.equals("Lukk")) {
                addDecisionListItemFrame.setVisible(false);
            }
        }
    }

    private class ActionListButtonListener implements ActionListener {

        JButton source;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Lukk")) {
                actionListFrame.setVisible(false);
            }
            if (text.equals("Angre")) {
                actionListFrame.setTable(actionlist, client.getProjectUsers());
                actionlist = client.getActionListToProject(client.getSelectedProject().getId());
            }
            if (text.equals("Lagre")) {
                String intro = actionListFrame.getActionlistIntroTextArea().getText();

                if(actionListFrame.getActionlistTable().isEditing()){
                    actionListFrame.getActionlistTable().getCellEditor().stopCellEditing();
                }

                for (int i = 0; i < actionlist.size(); i++) {
                    String desc = (String) actionListFrame.getActionlistTable().getModel().getValueAt(i, 0);
                    String startDate = (String) actionListFrame.getActionlistTable().getModel().getValueAt(i, 1);
                    String endDate = (String) actionListFrame.getActionlistTable().getModel().getValueAt(i, 2);
                    String responsible = (String) actionListFrame.getActionlistTable().getModel().getValueAt(i, 3);
                    String status = (String) actionListFrame.getActionlistTable().getModel().getValueAt(i, 4);
                    actionlist.get(i).setDescription(desc);
                    actionlist.get(i).setStartDate(startDate);
                    actionlist.get(i).setEndDate(endDate);
                    actionlist.get(i).setResponsible(responsible);
                    actionlist.get(i).setStatus(status);
                }
                client.editActionList(actionlist);
                System.out.println(intro);
                client.editActionListIntro(client.getSelectedProject().getId(), intro);
                client.sendActionlistUpdates();
                client.sendActivityUpdates();
                updateActionList();
                updateActivityList();
                activityListPanel.getActivityJList().clearSelection();
                activityInfoPanel.setVisible(false);

            }
        }
    }

    private class AddSessionButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            mainSessionPanel.addSessionPanel();
            for (int i = 0; i < teams.size(); i++) {
                TeamSessionInfoPanel infoPanel = new TeamSessionInfoPanel();
                infoPanel.editButtonPressed();
                for (int j = 0; j < mainSessionPanel.getSessionPanels().size(); j++) {
                    mainSessionPanel.getSessionPanelForTab(j).editButtonClicked();
                    mainSessionPanel.getSessionPanelForTab(j).getSessionDateTextField().addMouseListener(tfcl);
                }
                ArrayList<User> users = client.getUsersToTeam(teams.get(i).getId());
                for (int j = 0; j < users.size(); j++) {
                    infoPanel.getTeamMemberListModel().addElement(users.get(j).getFullname());
                    infoPanel.getUsers().add(users.get(j));

                }

                ArrayList<String> places = client.getAllPlaces();

                mainFrame.getMainSessionPanel().getSessionPanels().get(mainFrame.getMainSessionPanel().getSessionPanels().size() - 1).getSessionPlaceModel().removeAllElements();

                for (int j = 0; j < places.size(); j++) {
                    mainFrame.getMainSessionPanel().getSessionPanels().get(mainFrame.getMainSessionPanel().getSessionPanels().size() - 1).getSessionPlaceModel().addElement(places.get(j));
                }
                infoPanel.getFacilitatorCheckBox().setVisible(false);
                infoPanel.getSecretaryCheckBox().setVisible(false);
                infoPanel.getCustomerCheckBox().setVisible(false);

                mainFrame.getMainSessionPanel().getSessionPanelForTab(mainSessionPanel.getSessionsTabbedPane().getTabCount() - 1).addTeamTab(infoPanel, teams.get(i).getName());
                client.getSessions().add(new Session(0));

                //Må legge til roler i usersRoles.
                mainFrame.getMainSessionPanel().getSessionPanels() // henter alle sesjonspanel-lista
                        .get(mainFrame.getMainSessionPanel().getSessionPanels().size() - 1) //henter den nye som har blitt opprettet
                        .getLastteamSessionOnfoPanel() //henter siste teampanel
                        .getTeamMemberList() //
                        .addListSelectionListener(new SessionTeamMemberListSelectionListener());
                if (i == 0) {
                    ArrayList<addUserRoles> roles = client.getUserRolesProject(client.getSelectedProject().getId(), teams.get(i).getId());
                    System.out.println("hvor mange blir lagt til her " + roles.size());
                    for (int j = 0; j < roles.size(); j++) {
                        mainFrame.getMainSessionPanel().getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(i).getUserRoles().add(roles.get(j));
                    }
                    int t =mainFrame.getMainSessionPanel().getSessionPanels().get(0).getTeamSessionInfoPanels().get(0).getUserRoles().size();
                    System.out.println("så mange brukere ble lagt til i første team " + t);
                    infoPanel.getFacilitatorCheckBox().setVisible(true);
                    infoPanel.getSecretaryCheckBox().setVisible(true);
                    infoPanel.getCustomerCheckBox().setVisible(true);
                    // her blir listeners lagt til
                    mainSessionPanel.getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(0).
                            getTeamMemberList().addListSelectionListener(new SessionTeamMemberListSelectionListener());
                    mainSessionPanel.getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(0).
                            getFacilitatorCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                    mainSessionPanel.getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(0).
                            getCustomerCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                    mainSessionPanel.getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(0).
                            getSecretaryCheckBox().addActionListener(new TeamSessionInfoPanelButtonListener());
                    mainSessionPanel.getEditSessionButton().setText("Lagre");
                } else {
                    ArrayList<addUserRoles> roles = client.getUserRolesProject(client.getSelectedProject().getId(), teams.get(i).getId());
                    System.out.println("Enn her da?" + roles.size());
                    for (int j = 0; j < roles.size(); j++) {
                        mainFrame.getMainSessionPanel().getSessionPanels().get(mainSessionPanel.getSessionPanels().size() - 1).getTeamSessionInfoPanels().get(i).getUserRoles().add(roles.get(j));

                    }
                    int t =mainFrame.getMainSessionPanel().getSessionPanels().get(0).getTeamSessionInfoPanels().get(0).getUserRoles().size();
                    System.out.println("så mange brukere ble lagt til i første team " + t);
                }
            }
        }
    }

    private class RemoveSessionButtonListener implements ActionListener {

        int k;
        String[] ka;

        public void actionPerformed(ActionEvent e) {
            if (!mainSessionPanel.getSessionPanels().isEmpty()) {
                k = JOptionPane.showOptionDialog(null, "Er du sikker på at du vil utføre slettingen?", "Bekreftelse", JOptionPane.YES_NO_OPTION,
                        JOptionPane.PLAIN_MESSAGE, null, ka, "");
                if (k == JOptionPane.YES_OPTION) {
                    client.deleteSession(new Session(mainSessionPanel.getSelectedSessionPanel().getSessionId()));
                    client.updateSessionList();
                    mainSessionPanel.removeSessionPanel((SessionPanelForTabbedPane) mainSessionPanel.getSessionsTabbedPane().getSelectedComponent());
                    client.sendSessionUpdates();
                    updateSessionPanels();
                }
            }
        }
    }

    private class RemoveTeamButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            JButton source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Rediger") && addUsersToProjectFrame.getDeleteTeamButton().isEnabled()) {
                addUsersToProjectFrame.editButtonPressed();
                newProjectFrame.getProjectInfoPanel().getCreateProjectButton().setText("Oppdater");
                newProjectFrame.getProjectInfoPanel().editButtonPressed();
            } else if(addUsersToProjectFrame.getDeleteTeamButton().isEnabled()) {
                User u = new User();
                int teamId = addUsersToProjectFrame.getTeamInfoPanels().get(
                        addUsersToProjectFrame.getSelectedTeam()).getTeamId();
                ArrayList<String> tempUsers = new ArrayList<String>();
                for (int i = 0; i < addUsersToProjectFrame.getTeamInfoPanels().get(
                        addUsersToProjectFrame.getSelectedTeam()).getTeamMemberListModel().size(); i++) {
                    tempUsers.add((String) addUsersToProjectFrame.getTeamInfoPanels().get(
                            addUsersToProjectFrame.getSelectedTeam()).getTeamMemberListModel().getElementAt(i));
                    u = addUsersToProjectFrame.getTeamInfoPanels().get(
                            addUsersToProjectFrame.getSelectedTeam()).getUsers().get(i);
                }
                for (int i = 0; i < tempUsers.size(); i++) {
                    addUsersToProjectFrame.getUsersListModel().addElement(tempUsers.get(i));
                    addUsersToProjectFrame.getUsers().add(u);
                }
                addUsersToProjectFrame.getTeamInfoPanels().remove(addUsersToProjectFrame.getSelectedTeam());
                addUsersToProjectFrame.getTeamsTabbedPane().remove(addUsersToProjectFrame.getSelectedTeam());
                if (teamId > 0) {
                    client.deleteTeam(teamId);

                }

            }
        }
    }

    private class SaveActivityButtonListener implements ActionListener {

        JButton source;
        String text;

        public void actionPerformed(ActionEvent e) {
            source = (JButton) e.getSource();
            text = source.getText();

            if (text.equals("Opprett")) {
                if (activityInfoPanel.getStartDate().length() == 10 && activityInfoPanel.getEndDate().length() == 10) {
                    client.createActivity(activityInfoPanel.getActivityName(), activityInfoPanel.getStartDate(), activityInfoPanel.getEndDate(),
                            activityInfoPanel.getResponsible(), activityInfoPanel.getStatus(), activityInfoPanel.getDescription(),
                            activityInfoPanel.getGoals(), activityInfoPanel.getActivityLocation(), activityInfoPanel.isOnActionList());
                    activityInfoPanel.saveActivityButtonClicked();
                    activities = client.getActivitiesForSelectedProject();
                    activityListPanel.addActivity(activityInfoPanel.getActivityName());
                    activityListPanel.getActivityJList().setEnabled(true);
                    activityListPanel.getNewActivityButton().setFocusable(true);
                    activityListPanel.getActivityJList().setSelectedIndex(activityListPanel.getActivityListModel().size() - 1);
                    activityInfoPanel.getStartDateTextField().removeMouseListener(tfcl);
                    activityInfoPanel.getEndDateTextField().removeMouseListener(tfcl);
                    activityInfoPanel.setBorderTitle(activityInfoPanel.getActivityName());
                    updateActivityList();
                    client.sendActivityUpdates();
                    activityListPanel.getDeleteActivityButton().setText("Slett");
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst skriv inn dato");
                }


            } else if (text.equals("Rediger")) { // det står Rediger på knappen
                activityInfoPanel.getActivityResponsibleModel().removeAllElements();
                activityInfoPanel.getBoundToSessionModel().removeAllElements();
                activityListPanel.getActivityJList().setEnabled(false);
                activityListPanel.getNewActivityButton().setEnabled(false);
                for (int i = 0; i < client.getProjectUsers().size(); i++) {
                    activityInfoPanel.getActivityResponsibleModel().addElement(client.getProjectUsers().get(i).getFullname());
                }
                activityInfoPanel.getActivityResponsibleModel().setSelectedItem(client.getSelectedActivity().getResponsible());
                if (client.getNumberOfSessions() > 0) {
                    for (int i = 0; i < client.getNumberOfSessions(); i++) {
                        activityInfoPanel.getBoundToSessionModel().addElement(client.getSessionName(i));
                    }
                }
                activityInfoPanel.getBoundToSessionModel().setSelectedItem(client.getSessionBoundToActivity());
                activityInfoPanel.editActivityButtonClicked();
                activityInfoPanel.getStartDateTextField().addMouseListener(tfcl);
                activityInfoPanel.getEndDateTextField().addMouseListener(tfcl);

            } else if (text.equals("Lagre")) {

                if (activityInfoPanel.getStartDate().length() == 10 && activityInfoPanel.getEndDate().length() == 10) {
                    client.editActivity(activityInfoPanel.getActivityName(), activityInfoPanel.getStartDate(), activityInfoPanel.getEndDate(),
                            activityInfoPanel.getResponsible(), activityInfoPanel.getStatus(), activityInfoPanel.getDescription(),
                            activityInfoPanel.getGoals(), activityInfoPanel.getActivityLocation(), activityInfoPanel.isOnActionList());
                    activityInfoPanel.saveActivityButtonClicked();
                    client.updateActivityList();
                    activities = client.getActivitiesForSelectedProject();
                    activityListPanel.getActivityJList().setEnabled(true);
                    activityListPanel.getNewActivityButton().setEnabled(true);
                    activityInfoPanel.getStartDateTextField().removeMouseListener(tfcl);
                    activityInfoPanel.getEndDateTextField().removeMouseListener(tfcl);
                    activityInfoPanel.setBorderTitle(activityInfoPanel.getActivityName());

                    client.sendActivityUpdates();
                    updateActivityList();
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst skriv inn dato");
                }


            }
        }
    }

    private class DeleteActivityButtonListener implements ActionListener {

        int k;
        String[] ka = {"Yes", "No"};
        JButton source;
        String text;

        public void actionPerformed(ActionEvent e) {
            source = (JButton) e.getSource();
            text = source.getText();

            if (text.equals("Avbryt")) {
                activityInfoPanel.setVisible(false);
                activityInfoPanel.clearInput();
                activityListPanel.getActivityJList().setEnabled(true);
                source.setText("Slett");
            } else if (!activityListPanel.getActivityJList().isSelectionEmpty()) {

                k = JOptionPane.showOptionDialog(null, "Er du sikker på at du vil utføre slettingen?", "Bekreftelse", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
                        ka, "Gtfo");
                if (k == JOptionPane.YES_OPTION) {
                    if (activityListPanel.getActivityJList().getSelectedIndex() < activities.size()) {
                        client.deleteActivity();
                    }
                    activityInfoPanel.setVisible(false);
                    activities = client.getActivitiesForSelectedProject();
                    updateActivityList();
                    client.sendActivityUpdates();

                }

            }
        }
    }

    private class BoundToSessionActivityListener implements ActionListener {

        String text = "";

        public void actionPerformed(ActionEvent e) {
            JComboBox box = (JComboBox) e.getSource();
            text = (String) box.getSelectedItem();
            if (text != null) {
                for (int i = 0; i < client.getNumberOfSessions(); i++) {
                    if (text.equals(client.getSessions().get(i).getName())) {
                        activityInfoPanel.boundToSession(client.getSessions().get(i).getDate());
                        activityInfoPanel.getStartDateTextField().removeMouseListener(tfcl);
                        activityInfoPanel.getEndDateTextField().removeMouseListener(tfcl);
                        break;
                    }
                }
                if (text.equals("Ingen tilknytning")) {
                    activityInfoPanel.notBoundToSession();
                    activityInfoPanel.getStartDateTextField().addMouseListener(tfcl);
                    activityInfoPanel.getEndDateTextField().addMouseListener(tfcl);
                }

            }
        }
    }

    private class CreateProjectButtonListener implements ActionListener {

        String projectName;
        String projectDesc;
        String projectGoals;
        String projectLeader;
        ArrayList<User> projectUsers = new ArrayList<User>();
        String teamName;

        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            String text = source.getText();
            if (text.equals("Opprett")) {
                projectName = projectInfoPanel.getProjectNameTextField().getText();
                projectDesc = projectInfoPanel.getProjectDescTextArea().getText();
                projectGoals = projectInfoPanel.getProjectGoalTextArea().getText();
                projectLeader = (String) projectInfoPanel.getProjectLeaderDropDown().getSelectedItem();
                if (!projectName.trim().equals("")) {
                    int projectId = client.createProject(projectName, projectDesc, projectGoals, projectLeader);
                    //client.deleteUserToProject(projectId);
                    for (int i = 0; i < addUsersToProjectFrame.getTeamInfoPanels().size(); i++) {
                        teamName = addUsersToProjectFrame.getTeamInfoPanels().get(i).getTeamNameTextField().getText();
                        for (int j = 0; j < addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().size(); j++) {

                            projectUsers.add(addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().get(j));
                        }
                        int teamId = client.createTeam(teamName);
                        int roleId = 0;
                        //role id. Fasilitator =2, secretær = 3, kunde = 4, expert =5
                        if (i == 0) {
                            ArrayList<User> tempUser = new ArrayList<User>();
                            ArrayList<addUserRoles> userRoles = addUsersToProjectFrame.getTeamInfoPanels().get(i).getUserRoles();
                            for (int j = 0; j < userRoles.size(); j++) {
                                if (userRoles.get(j).isFasilitator()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 2;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }
                                if (userRoles.get(j).isSecretary()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 3;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                    if (userRoles.get(j).isCustomer()) {
                                        tempUser.add(userRoles.get(j).getUser());
                                        roleId = 4;
                                        client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                        tempUser.clear();
                                    }
                                }
                                if (!userRoles.get(j).isSomething()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 5;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }

                            }
                        } else {
                            roleId = 5;
                            client.registerUserToProject(projectId, projectUsers, teamId, roleId);

                        }
                        projectUsers.clear();
                    }
                    projectInfoPanel.clearInput();
                    addUsersToProjectFrame.getUsersListModel().clear();
                    client.updateProjectList();
                    newProjectFrame.setVisible(false);
                    addUsersToProjectFrame.clearInput();
                }
            } //Edit project
            else if (text.equals("Rediger")) {
                newProjectFrame.getProjectInfoPanel().editButtonPressed();
                newProjectFrame.getProjectInfoPanel().getCreateProjectButton().setText("Oppdater");
            } else {
                projectName = projectInfoPanel.getProjectNameTextField().getText();

                if (!projectName.trim().equals("")) {
                    projectDesc = projectInfoPanel.getProjectDescTextArea().getText();
                    projectGoals = projectInfoPanel.getProjectGoalTextArea().getText();
                    projectLeader = (String) projectInfoPanel.getProjectLeaderDropDown().getSelectedItem();
                    int projectId = client.getSelectedProject().getId();
                    client.editProject(projectId, projectName, projectDesc, projectGoals, projectLeader);
                    client.deleteUserToProject(projectId);
                    for (int i = 0; i < addUsersToProjectFrame.getTeamInfoPanels().size(); i++) {
                        teamName = addUsersToProjectFrame.getTeamInfoPanels().get(i).getTeamNameTextField().getText();
                        for (int j = 0; j < addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().size(); j++) {
                            projectUsers.add(addUsersToProjectFrame.getTeamInfoPanels().get(i).getUsers().get(j));
                        }
                        int teamId = 0;
                        if (addUsersToProjectFrame.getTeamInfoPanels().get(i).getTeamId() > 0) {
                            teamId = addUsersToProjectFrame.getTeamInfoPanels().get(i).getTeamId();
                            client.editTeam(teamId, teamName);
                        } else {
                            teamId = client.createTeam(teamName);
                        }
                        int roleId = 0;
                        //role id. Fasilitator =2, secretær = 3, kunde = 4, expert =5

                        if (i == 0) {
                            ArrayList<User> tempUser = new ArrayList<User>();
                            ArrayList<addUserRoles> userRoles = addUsersToProjectFrame.getTeamInfoPanels().get(i).getUserRoles();
                            for (int j = 0; j < userRoles.size(); j++) {
                                if (userRoles.get(j).isFasilitator()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 2;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }
                                if (userRoles.get(j).isSecretary()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 3;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }
                                if (userRoles.get(j).isCustomer()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 4;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }
                                if (!userRoles.get(j).isSomething()) {
                                    tempUser.add(userRoles.get(j).getUser());
                                    roleId = 5;
                                    client.registerUserToProject(projectId, tempUser, teamId, roleId);
                                    tempUser.clear();
                                }

                            }
                        } else {
                            roleId = 5;
                            client.registerUserToProject(projectId, projectUsers, teamId, roleId);

                        }
                        projectUsers.clear();

                    }
                    showProjectObjects();
                    projectInfoPanel.clearInput();
                    addUsersToProjectFrame.getUsersListModel().clear();
                    client.updateProjectList();
                    newProjectFrame.setVisible(false);
                    addUsersToProjectFrame.clearInput();
                }
            }
            client.sendProjectUpdates();

        }
    }

    private class WindowListener extends WindowAdapter {

        public void windowClosing(WindowEvent we) {
            client.disconnectFromServer();
        }
    }

    private class ChatTextListener extends KeyAdapter {

        int key;

        public void keyPressed(KeyEvent e) {
            key = e.getKeyCode();
            if (key == e.VK_ENTER) {
                chatPanel.getInputText().setCaretPosition(0);
                chatPanel.getSendButton().doClick();
            }
        }

        public void keyReleased(KeyEvent e) {
            key = e.getKeyCode();
            if (key == e.VK_ENTER) {
                chatPanel.getInputText().setCaretPosition(0);
            }
        }
    }

    private class resourceMenuActionListener implements ActionListener {

        JMenuItem source;

        public void actionPerformed(ActionEvent ae) {
            source = (JMenuItem) ae.getSource();
            String text = source.getText();
            ArrayList<ResourceType> types = new ArrayList<ResourceType>();
            ArrayList<Resource> resources = new ArrayList<Resource>();
            try {
                types = client.getAllResourceTypes();
            } catch (RemoteException ex) {
                Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (text.equals("Ny ressurs")) {

                for (int i = 0; i < types.size(); i++) {
                    resourceFrame.getResourceTypeComboModel().addElement(types.get(i).getType());
                }
                resourceFrame.setVisible(true);
                types.clear();
            } else {
                updateResources();
                resourceToProjectFrame.setVisible(true);
            }

        }
    }

    private class resourceButtonListener implements ActionListener {

        JButton source;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Ny Type")) {
                resourceFrame.newTypeButtonPressed();
            }
            if (text.equals("Lukk")) {
                resourceFrame.setVisible(false);
                resourceFrame.clearInput();

            }
            if (text.equals("Angre")) {
                resourceFrame.regretButtonPressed();
            }
            if (text.equals("Opprett")) {
                String resourceName = resourceFrame.getResourceNameTextField().getText();
                String temp = "";
                if (resourceFrame.getResourceTypeTextField().isShowing()) {
                    temp = resourceFrame.getResourceTypeTextField().getText();
                } else {
                    temp = resourceFrame.getResourceTypeComboModel().getSelectedItem().toString();
                }
                if (resourceName.length() > 3 && temp.length() > 1) {
                    int resourceTypeId = 0;
                    String resourceType = "";

                    if (resourceFrame.getResourceTypeTextField().isShowing()) {
                        resourceType = resourceFrame.getResourceTypeTextField().getText();
                        try {
                            resourceTypeId = client.registerResourceType(resourceType);
                            //Lagre ne resurs
                        } catch (RemoteException ex) {
                            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        resourceType = resourceFrame.getResourceTypeComboModel().getSelectedItem().toString();
                        try {
                            ArrayList<ResourceType> types = client.getAllResourceTypes();
                            for (int i = 0; i < types.size(); i++) {
                                if (types.get(i).getType().equals(resourceType)) {
                                    resourceTypeId = types.get(i).getId();
                                }
                            }
                        } catch (RemoteException ex) {
                            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    try {
                        resourceToProjectFrame.getAvailableResourceListModel().addElement(resourceName);
                        int[] ids = client.registerResource(resourceName, resourceType, resourceTypeId);
                        resourceToProjectFrame.getAvailableResources().add(new Resource(ids[1], resourceName, ids[0]));
                    } catch (RemoteException ex) {
                        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    client.getAllResourceToProject(client.getSelectedProject().getId());
                    resourceFrame.getResourceTypeTextField().setVisible(false);
                    resourceFrame.setVisible(false);
                    resourceFrame.clearInput();
                    resourceFrame.getResourceTypeComboModel().removeAllElements();
                } else {
                    if (resourceName.length() < 4) {
                        JOptionPane.showMessageDialog(null, "Ressursnavn må være minst fire tegn");
                    } else {
                        JOptionPane.showMessageDialog(null, "Ressurstype må være minst to tegn");
                    }
                }

            }
        }
    }

    private class userMenuActionListener implements ActionListener {

        JMenuItem source;

        public void actionPerformed(ActionEvent ae) {
            source = (JMenuItem) ae.getSource();
            String text = source.getText();
            if (text.equals("Ny bruker")) {
                addUserFrame.clearInputt();
                addUserFrame.setVisible(true);
            }
            if (text.equals("Endre egen brukerinformasjon")) {
                editUserFrame.setVisible(true);
                User u = client.getUserToUsername(client.getLoginn().getUsername());
                ArrayList<String> rolles = client.getRolesToUser(u.getId());
                editUserFrame.getFullnameField().setText(u.getFullname());
                editUserFrame.getEpostField().setText(u.getUsername());
                editUserFrame.getEkspertiseField().setText(u.getExpertise());
                editUserFrame.getWorkplaceField().setText(u.getWorkplace());
                editUserFrame.getConfirmedPasswordField().setText("");
                editUserFrame.getOldPasswordField().setText("");
                editUserFrame.getNewPasswordField().setText("");
                for (int i = 0; i < rolles.size(); i++) {
                    if (rolles.get(i).equals("Prosjektleder")) {
                        editUserFrame.getProjectLeaderCheckBox().setSelected(true);
                    }
                    if (rolles.get(i).equals("Fasilitator")) {
                        editUserFrame.getFasilitatorCheckBox().setSelected(true);
                    }
                    if (rolles.get(i).equals("Sekretær")) {
                        editUserFrame.getSecretaryCheckBox().setSelected(true);
                    }
                }
            }
            if (text.equals("Brukerliste")) {
                showUserList();
            }
        }
    }

    private class IPMenuActionListener extends MouseAdapter {

        public void mouseClicked(MouseEvent ae) {
            ipFrame.setVisible(true);
            ipFrame.getIPadresseTextField().setText(client.getIp());

        }
    }

    private class IPFramButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            JButton source = (JButton) ae.getSource();
            String text = source.getText();
            if (text.equals("Lagre")) {
                String IP = ipFrame.getIPadresseTextField().getText();
                String[] temp;
                temp = IP.split("\\.");

                boolean ok = true;
                if (temp.length != 4) {
                    ok = false;
                } else {
                    for (int i = 0; i < temp.length; i++) {
                        if (temp[i].length() < 1 || temp[i].length() > 3) {
                            ok = false;
                        }
                        for (int j = 0; j < temp[i].length(); j++) {
                            if (!Character.isDigit(temp[i].charAt(j))) {
                                ok = false;
                            }
                        }
                    }
                }

                if (ok) {
                    //Write to propfile
                    WriteToPropertiesFile wpf = new WriteToPropertiesFile();
                    HashMap map = new HashMap();
                    map.put("ip", IP);
                    String path = System.getProperty("user.dir");
                    try {
                        wpf.writeToFile(map, path + "/settings.properties");
                    } catch (Exception ex) {
                        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    JOptionPane.showMessageDialog(null, "IP OK\nKlienten må restartes.");
                    //client.readProperties();

                    //client.updateServer();
                    ipFrame.getSaveButton().setText("Restart Client");
                } else {


                    JOptionPane.showMessageDialog(null, "Ip adressen du skrev inn har ugyldig format");
                }
            } else {
                String path = System.getProperty("user.dir");
                Runtime runtime = Runtime.getRuntime();
                try {
                    Process proc = runtime.exec("java -jar " + path + "/Client.jar");
                } catch (IOException ex) {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.exit(0);
                ipFrame.setVisible(false);
            }

        }
    }

    private class MenuActionListener implements ActionListener {

        JMenuItem source;
        String text;

        public MenuActionListener() {
        }

        public void actionPerformed(ActionEvent e) {
            source = (JMenuItem) e.getSource();
            text = source.getText();
            if (text.equals("Nytt prosjekt")) {
                newProjectClicked();

            } else if (text.equals("Vis prosjektinformasjon")) {
                if (client.getSelectedProject().getId() > 0) {
                    newProjectFrame.setVisible(true);
                    newProjectFrame.getProjectInfoPanel().getProjectDescTextArea().setText(client.getSelectedProject().getDesc());
                    newProjectFrame.getProjectInfoPanel().getProjectGoalTextArea().setText(client.getSelectedProject().getGoals());
                    newProjectFrame.getProjectInfoPanel().getProjectNameTextField().setText(client.getSelectedProject().getName());

                    if(client.isAdmin())newProjectFrame.getProjectInfoPanel().getCreateProjectButton().setText("Rediger");
                    else newProjectFrame.getProjectInfoPanel().getCreateProjectButton().setText("Lukk");
                    newProjectFrame.getProjectInfoPanel().isInfoPanel();
                    newProjectFrame.getProjectInfoPanel().getAddProjectUsersButton().setText("Vis Teamoppdeling");
                    addUsersToProjectFrame.isInfoPanel();
                    System.out.println(client.isAdmin());
                    System.out.println(client.isAdmin());
                    if(!client.isAdmin())addUsersToProjectFrame.getDeleteTeamButton().setEnabled(false);
                    else addUsersToProjectFrame.getDeleteTeamButton().setEnabled(true);
                    ArrayList<Team> teams = client.getTeamsToProject(client.getSelectedProject().getId());
                    int teamnumber = -1;
                    for (int j = 0; j < teams.size(); j++) {
                        ArrayList<User> users = client.getUsersToTeam(teams.get(j).getId());
                        for (int k = 0; k < users.size(); k++) {
                            if (users.get(k).getId() == client.getUserToUsername(client.getLoginn().getUsername()).getId()) {
                                teamnumber = j;
                            }
                        }
                    }
                    if (teamnumber ==0){
                        addUsersToProjectFrame.getDeleteTeamButton().setEnabled(true);
                    }





                    addUsersToProjectFrame.clearInput();
                    System.out.println(addUsersToProjectFrame.getDeleteTeamButton().isEnabled());
                    addUsersToProjectFrame.getUsersListModel().removeAllElements();
                    addUsersToProjectFrame.getUsers().clear();
                    addUsersToProjectFrame.getTeamInfoPanels().clear();
                    addUsersToProjectFrame.getTeamsTabbedPane().removeAll();
                    addUsersToProjectFrame.setUsers(client.getAllUsers());
                    ArrayList<User> projectUser = client.getProjectUsers();
                    newProjectFrame.getProjectInfoPanel().getAddedUserListModel().removeAllElements();
                    for (int i = 0; i < projectUser.size(); i++) {
                        newProjectFrame.getProjectInfoPanel().getAddedUserListModel().addElement(projectUser.get(i).getFullname());
                    }

                    for (int i = 0; i < teams.size(); i++) {
                        ArrayList<User> users = client.getUsersToTeam(teams.get(i).getId());
                        addUsersToProjectFrame.showTeam(teams.get(i), users, client);
                        addUsersToProjectFrame.getTeamInfoPanels().get(addUsersToProjectFrame.getTeamInfoPanels().size() - 1).getDeleteTeamButton().addActionListener(rtbl);
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getTeamMembersList().addListSelectionListener(new TeamMemberListSelectionListener());
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getFasilitatorCheckBox().addActionListener(new TeamInfoPanelButtonListener());
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getFasilitatorCheckBox().setFocusable(false);
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getSecretaryCheckBox().addActionListener(new TeamInfoPanelButtonListener());
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getSecretaryCheckBox().setFocusable(false);
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getCustomerCheckBox().addActionListener(new TeamInfoPanelButtonListener());
                        addUsersToProjectFrame.getTeamInfoPanels().get(0).getCustomerCheckBox().setFocusable(false);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst velg et prosjekt først.");
                }

            } else if (text.equals("Aksjonsliste")) {
                if (client.getSelectedProject().getId() > 0) {
                    actionListFrame.setVisible(true);
                    actionListFrame.getActionlistIntroTextArea().setText(client.getActionListIntro(client.getSelectedProject().getId()));
                    ArrayList<ActionList> actionList = client.getActionListToProject(client.getSelectedProject().getId());
                    actionListFrame.setTable(actionList, client.getProjectUsers());
                    //actionListFrame.getActionlistTable().getModel().addTableModelListener(new ActionListListener());
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst velg et prosjekt først.");
                }

            } else if (text.equals("Beslutningsliste")) {
                if (client.getSelectedProject().getId() > 0) {
                    ArrayList<DecisionList> decisionList = client.getDecisionListToProject(client.getSelectedProject().getId());
                    ArrayList<Session> sessions = client.getSessions();
                    decisionListFrame.setTabel(decisionList, sessions, client.getSelectedProject().getName());
                    decisionListFrame.setVisible(true);
                    decisionListFrame.getIntroTextArea().setText(client.getDecisionListIntro(client.getSelectedProject().getId()));
                } else {
                    JOptionPane.showMessageDialog(null, "Vennligst velg et prosjekt først.");
                }
            } else {
                System.out.println("Forhåpentligvis trykket på et prosjekt");
                System.out.println("Actioncommand er " + source.getActionCommand());
                for (int i = 0; i < client.getAllProjects().size(); i++) {
                    if (client.getAllProjects().get(i).getId() == Integer.parseInt(source.getActionCommand())) {
                        try {
                            System.out.println(client.getClientIp());
                            client.getServer().quit(client.getCallback(), client.getClientIp());
                            client.projectClicked(Integer.parseInt(source.getActionCommand()));

                            showProjectObjects();
                        } catch (RemoteException ex) {
                            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
    }

    private class CountDownButtonListener implements ActionListener {

        JButton source;
        String text;

        public void actionPerformed(ActionEvent ae) {
            source = (JButton) ae.getSource();
            text = source.getText();
            if (text.equals("Ny nedtelling")) {
                String time = JOptionPane.showInputDialog(null, "Hvor mange minutter?");
                int min = 0;
                try {
                    min = Integer.parseInt(time);
                    startCountDown(min);
                    client.sendCountDownStart(min);
                    mainSessionPanel.getStopCountdownButton().setText("Stopp nedtelling");

                } catch (Exception e) {
                }
            } else if (text.equals("Stopp nedtelling")) {
                stopCountDown();
                client.sendCountDownStop();
                mainSessionPanel.getStopCountdownButton().setText("Fortsett");
            } else if (text.equals("Fortsett")) {
                resumeCountDown();
                client.sendCountDownResume();
                mainSessionPanel.getStopCountdownButton().setText("Stopp nedtelling");
            }
        }
    }

    private class TextFieldClickListener extends MouseAdapter {

        JTextField sourceTextField;

        public void mouseClicked(java.awt.event.MouseEvent e) {
            sourceTextField = (JTextField) e.getSource();
            calendarFrame.setVisible(true);
            calendarFrame.getOkButton().addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    sourceTextField.setText(calendarFrame.getSelectedDate());
                    calendarFrame.setVisible(false);
                    calendarFrame.getOkButton().removeActionListener(this);
                }
            });
        }
    }

    private class CreateSessionPlanListener implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            sessionPlan = new SessionPlan(client.getServer(), client.getSelectedProject().getId());
            try {
                sessionPlan.createPlan();
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private class ActivityListSelectionListener extends MouseAdapter {

        String selectedA = "";
        int mod = 0;

        public void mouseClicked(MouseEvent e) {

            selectedA = (String) activityListPanel.getActivityJList().getSelectedValue();
            client.setSelectedActivity(selectedA);
            if (client.getNumberOfSessions() > 0) {
                for (int i = 0; i < client.getNumberOfSessions(); i++) {
                    activityInfoPanel.getBoundToSessionModel().addElement(client.getAllSessionNames().get(i));
                }
            }

            activityInfoPanel.getBoundToSessionDropDown().setSelectedItem(client.getSessionBoundToActivity());
            activityInfoPanel.showActivityInfo(client.getSelectedActivity().getActivityName(),
                    client.getSelectedActivity().getStarteDate(),
                    client.getSelectedActivity().getEndDate(),
                    client.getSelectedActivity().getStatus(), client.getSelectedActivity().getDescription(),
                    client.getSelectedActivity().getGoals(), client.getSelectedActivity().getLocation(),
                    client.getSelectedActivity().getResponsible(), client.getSelectedActivity().isOnActionList());
            activityInfoPanel.setVisible(true);
            activityInfoPanel.getStartDateTextField().removeMouseListener(tfcl);
            activityInfoPanel.getEndDateTextField().removeMouseListener(tfcl);
        }
    }
}
